Download code/src/gate_controls.py from PratikBuilds/modelclinic-experiment-001: direct link, hf CLI and curl.
- Browser
- Download file 23.1 kB
-
https://huggingface.co/datasets/PratikBuilds/modelclinic-experiment-001/resolve/main/code/src/gate_controls.py
- Command line
-
hf download hf://datasets/PratikBuilds/modelclinic-experiment-001/code/src/gate_controls.py
-
curl -L -o gate_controls.py https://huggingface.co/datasets/PratikBuilds/modelclinic-experiment-001/resolve/main/code/src/gate_controls.py
23.1 kB
| """Utilities for signed constant and approximate rank-one layer controls. | |
| For a weight edit ``delta`` with shape ``[out_features, in_features]``, the | |
| best rank-one SVD approximation is ``u @ gate_vector.T``. At the edited | |
| linear's output, it produces the activation-dependent update | |
| ``(x @ gate_vector) * u``. A signed constant controller instead adds | |
| ``coefficient * u`` at every token. | |
| """ | |
| from __future__ import annotations | |
| from itertools import product | |
| import math | |
| from typing import Iterable, Mapping, Sequence | |
| import torch | |
| import torch.nn.functional as F | |
| def _as_delta(delta: torch.Tensor) -> torch.Tensor: | |
| if not torch.is_tensor(delta) or delta.ndim != 2: | |
| raise ValueError("delta must be a 2D [out_features, in_features] tensor") | |
| delta = delta.to(dtype=torch.float32) | |
| if delta.numel() == 0 or not torch.isfinite(delta).all(): | |
| raise ValueError("delta must be non-empty and finite") | |
| if torch.linalg.vector_norm(delta) == 0: | |
| raise ValueError("delta must be non-zero") | |
| return delta | |
| def _canonicalize(direction: torch.Tensor, paired: torch.Tensor | None = None): | |
| """Fix the SVD sign ambiguity by making the largest-magnitude entry positive.""" | |
| pivot = int(direction.abs().argmax().item()) | |
| if direction[pivot] < 0: | |
| direction = -direction | |
| if paired is not None: | |
| paired = -paired | |
| return direction, paired | |
| def decompose(delta: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: | |
| """Return canonical unit left direction and scaled right gate vector. | |
| The returned vectors satisfy ``u @ v.T == best_rank_one(delta)`` up to | |
| floating-point error, where ``u`` has shape ``[out]`` and ``v`` has shape | |
| ``[in]``. The sign convention makes serialized directions reproducible | |
| across repeated decompositions of the same tensor. | |
| """ | |
| delta = _as_delta(delta) | |
| left, singular_values, right = torch.linalg.svd(delta, full_matrices=False) | |
| direction = left[:, 0] | |
| gate_vector = singular_values[0] * right[0, :] | |
| direction, gate_vector = _canonicalize(direction, gate_vector) | |
| return direction, gate_vector | |
| def _as_activations(activations: torch.Tensor, in_features: int, device) -> torch.Tensor: | |
| if not torch.is_tensor(activations) or activations.ndim < 1: | |
| raise ValueError("activations must be a tensor with in_features in its last dimension") | |
| if activations.shape[-1] != in_features: | |
| raise ValueError( | |
| f"activation width mismatch: expected {in_features}, got {activations.shape[-1]}" | |
| ) | |
| flat = activations.to(device=device, dtype=torch.float32).reshape(-1, in_features) | |
| if flat.shape[0] == 0 or not torch.isfinite(flat).all(): | |
| raise ValueError("activations must contain at least one finite position") | |
| return flat | |
| def _as_activation_groups(activations, in_features: int, device) -> list[torch.Tensor]: | |
| """Normalize a tensor or one tensor per prompt to flattened activation rows.""" | |
| if torch.is_tensor(activations): | |
| raw_groups = [activations] | |
| elif isinstance(activations, (list, tuple)) and activations: | |
| raw_groups = list(activations) | |
| else: | |
| raise ValueError("activations must be a tensor or a non-empty list of prompt tensors") | |
| return [_as_activations(group, in_features, device) for group in raw_groups] | |
| def _weighted_mean(values: Sequence[torch.Tensor], prompt_weighting: str) -> torch.Tensor: | |
| if prompt_weighting == "token": | |
| return torch.cat([value.reshape(-1) for value in values]).mean() | |
| if prompt_weighting == "prompt": | |
| return torch.stack([value.reshape(-1).mean() for value in values]).mean() | |
| raise ValueError("prompt_weighting must be 'token' or 'prompt'") | |
| def fit_signed_constant( | |
| delta: torch.Tensor, | |
| activations, | |
| direction: torch.Tensor | None = None, | |
| *, | |
| prompt_weighting: str = "token", | |
| ) -> tuple[torch.Tensor, float]: | |
| """Fit the signed least-squares constant along an output direction. | |
| ``activations`` may be one tensor with any leading dimensions or one tensor | |
| per prompt; each must end in the input width of ``delta``. ``prompt_weighting`` | |
| is ``"token"`` for a pooled token mean or ``"prompt"`` for an equal mean of | |
| per-prompt gate means. If ``direction`` is omitted, the canonical leading | |
| left singular vector is used. The direction is normalized and sign-fixed; | |
| the returned coefficient is the mean scalar projection of ``delta @ x`` | |
| onto that direction. This minimizes summed squared error among constant | |
| updates constrained to the selected direction. | |
| """ | |
| delta = _as_delta(delta) | |
| if direction is None: | |
| direction, _ = decompose(delta) | |
| else: | |
| if not torch.is_tensor(direction) or direction.ndim != 1: | |
| raise ValueError("direction must be a 1D output vector") | |
| direction = direction.to(device=delta.device, dtype=torch.float32) | |
| if direction.shape[0] != delta.shape[0]: | |
| raise ValueError( | |
| f"direction width mismatch: expected {delta.shape[0]}, got {direction.shape[0]}" | |
| ) | |
| norm = torch.linalg.vector_norm(direction) | |
| if not torch.isfinite(norm) or norm == 0: | |
| raise ValueError("direction must be finite and non-zero") | |
| direction = direction / norm | |
| direction, _ = _canonicalize(direction) | |
| groups = _as_activation_groups(activations, delta.shape[1], delta.device) | |
| projections = [F.linear(group, delta) @ direction for group in groups] | |
| mean = _weighted_mean(projections, prompt_weighting) | |
| return direction, float(mean.item()) | |
| def signed_projection_rms( | |
| delta: torch.Tensor, | |
| activations, | |
| direction: torch.Tensor, | |
| *, | |
| prompt_weighting: str = "token", | |
| ) -> float: | |
| """Return RMS signed projection of the edit effect along ``direction``.""" | |
| delta = _as_delta(delta) | |
| if not torch.is_tensor(direction) or direction.ndim != 1: | |
| raise ValueError("direction must be a 1D output vector") | |
| direction = direction.to(device=delta.device, dtype=torch.float32) | |
| if direction.shape[0] != delta.shape[0]: | |
| raise ValueError("direction width mismatch") | |
| norm = torch.linalg.vector_norm(direction) | |
| if not torch.isfinite(norm) or norm == 0: | |
| raise ValueError("direction must be finite and non-zero") | |
| direction = direction / norm | |
| direction, _ = _canonicalize(direction) | |
| groups = _as_activation_groups(activations, delta.shape[1], delta.device) | |
| projections = [F.linear(group, delta) @ direction for group in groups] | |
| return float(_weighted_mean([value.square() for value in projections], prompt_weighting).sqrt().item()) | |
| def coefficient_grid( | |
| projection_rms: float, | |
| multipliers: Iterable[float] = (-2.0, -1.0, 0.0, 1.0, 2.0), | |
| ) -> list[float]: | |
| """Build a symmetric signed candidate grid scaled to a layer's edit effect.""" | |
| scale = float(projection_rms) | |
| if not math.isfinite(scale) or scale < 0: | |
| raise ValueError("projection_rms must be finite and non-negative") | |
| factors = [float(value) for value in multipliers] | |
| if not factors or any(not math.isfinite(value) for value in factors): | |
| raise ValueError("multipliers must contain finite values") | |
| return sorted({scale * factor for factor in factors}) | |
| def calibrate_layer( | |
| delta: torch.Tensor, | |
| activations, | |
| *, | |
| grid_multipliers: Iterable[float] = (-2.0, -1.0, 0.0, 1.0, 2.0), | |
| prompt_weighting: str = "token", | |
| ) -> dict: | |
| """Return JSON-safe factors and descriptive calibration metrics for a layer.""" | |
| delta = _as_delta(delta) | |
| direction, gate_vector = decompose(delta) | |
| summary = calibrate_direction( | |
| delta, | |
| activations, | |
| direction, | |
| grid_multipliers=grid_multipliers, | |
| prompt_weighting=prompt_weighting, | |
| ) | |
| summary["rank1_energy_fraction"] = summary.pop("direction_energy_fraction") | |
| summary["rank1_gate_vector"] = gate_vector.cpu().tolist() | |
| return summary | |
| def calibrate_direction( | |
| delta: torch.Tensor, | |
| activations, | |
| direction: torch.Tensor, | |
| *, | |
| grid_multipliers: Iterable[float] = (-2.0, -1.0, 0.0, 1.0, 2.0), | |
| prompt_weighting: str = "token", | |
| ) -> dict: | |
| """Calibrate any fixed direction against edit effects on disjoint activations. | |
| This supports independent or random control directions as well as the | |
| published edit's leading singular direction. The signed mean and RMS are | |
| projections of the exact weight-edit effect onto the supplied unit | |
| direction; no direction is inferred from ``delta`` here. | |
| """ | |
| delta = _as_delta(delta) | |
| if not torch.is_tensor(direction) or direction.ndim != 1: | |
| raise ValueError("direction must be a 1D output vector") | |
| direction = direction.to(device=delta.device, dtype=torch.float32) | |
| if direction.shape[0] != delta.shape[0]: | |
| raise ValueError("direction width mismatch") | |
| norm = torch.linalg.vector_norm(direction) | |
| if not torch.isfinite(norm) or norm == 0: | |
| raise ValueError("direction must be finite and non-zero") | |
| direction = direction / norm | |
| direction, _ = _canonicalize(direction) | |
| groups = _as_activation_groups(activations, delta.shape[1], delta.device) | |
| effects = [F.linear(group, delta) for group in groups] | |
| projections = [effect @ direction for effect in effects] | |
| energy = _weighted_mean([effect.square().sum(dim=-1) for effect in effects], prompt_weighting) | |
| if energy == 0: | |
| raise ValueError("calibration activations produce a zero edit effect") | |
| mean_coefficient = _weighted_mean(projections, prompt_weighting) | |
| rank_one_residual = [effect - projection.unsqueeze(-1) * direction | |
| for effect, projection in zip(effects, projections)] | |
| constant_residual = [effect - mean_coefficient * direction for effect in effects] | |
| rank_one_residual_energy = _weighted_mean( | |
| [residual.square().sum(dim=-1) for residual in rank_one_residual], prompt_weighting | |
| ) | |
| constant_residual_energy = _weighted_mean( | |
| [residual.square().sum(dim=-1) for residual in constant_residual], prompt_weighting | |
| ) | |
| projection_rms = _weighted_mean([projection.square() for projection in projections], prompt_weighting).sqrt() | |
| return { | |
| "direction": direction.cpu().tolist(), | |
| "signed_mean_coefficient": float(mean_coefficient.item()), | |
| "projection_rms": float(projection_rms.item()), | |
| "edit_effect_rms": float(energy.sqrt().item()), | |
| "direction_energy_fraction": float((1.0 - rank_one_residual_energy / energy).item()), | |
| "constant_residual_energy_fraction": float((constant_residual_energy / energy).item()), | |
| "coefficient_grid": coefficient_grid(float(projection_rms.item()), grid_multipliers), | |
| "activation_tokens": int(sum(group.shape[0] for group in groups)), | |
| "calibration_prompts": int(len(groups)), | |
| "prompt_weighting": prompt_weighting, | |
| } | |
| def controller_grid( | |
| projection_rms_by_layer: Mapping[str | int, float], | |
| multipliers: Iterable[float] = (-2.0, -1.0, 0.0, 1.0, 2.0), | |
| ) -> list[dict[str, float]]: | |
| """Enumerate a Cartesian grid with separately tunable coefficient per layer.""" | |
| ordered = [(str(layer), coefficient_grid(rms, multipliers)) | |
| for layer, rms in projection_rms_by_layer.items()] | |
| if not ordered: | |
| raise ValueError("at least one layer scale is required") | |
| return [dict(zip((layer for layer, _ in ordered), values)) | |
| for values in product(*(grid for _, grid in ordered))] | |
| def select_behavioral_controller( | |
| grid_results: Sequence[Mapping], | |
| signed_mean_by_layer: Mapping[str | int, float], | |
| *, | |
| score_key: str = "correct", | |
| ) -> dict: | |
| """Select the highest-scoring grid row, with stable prespecified tie-breaks. | |
| Each result must contain ``coefficients`` (a per-layer mapping) and a | |
| numeric behavioral score such as the number of calibration answers graded | |
| correct. Ties prefer coefficients closest in squared distance to the signed | |
| mean fit, then the smallest coefficient norm, then lexicographic order. | |
| Callers should retain every grid row and prompt-level score in the manifest. | |
| """ | |
| if not grid_results: | |
| raise ValueError("grid_results must contain at least one scored row") | |
| mean = {str(layer): float(value) for layer, value in signed_mean_by_layer.items()} | |
| if not mean or any(not math.isfinite(value) for value in mean.values()): | |
| raise ValueError("signed_mean_by_layer must contain finite coefficients") | |
| candidates = [] | |
| for row in grid_results: | |
| if "coefficients" not in row or score_key not in row: | |
| raise ValueError(f"each grid result needs coefficients and {score_key!r}") | |
| coefficients = {str(layer): float(value) for layer, value in row["coefficients"].items()} | |
| if set(coefficients) != set(mean): | |
| raise ValueError("grid result layers do not match signed_mean_by_layer") | |
| score = float(row[score_key]) | |
| if not math.isfinite(score) or any(not math.isfinite(value) for value in coefficients.values()): | |
| raise ValueError("grid scores and coefficients must be finite") | |
| distance = sum((coefficients[layer] - mean[layer]) ** 2 for layer in mean) | |
| magnitude = sum(value * value for value in coefficients.values()) | |
| stable = tuple(coefficients[layer] for layer in sorted(coefficients)) | |
| candidates.append((-score, distance, magnitude, stable, dict(row))) | |
| return min(candidates, key=lambda item: item[:4])[-1] | |
| def adjustment( | |
| x: torch.Tensor, | |
| direction: torch.Tensor, | |
| gate_vector: torch.Tensor | None = None, | |
| coefficient: float | torch.Tensor | None = None, | |
| ) -> torch.Tensor: | |
| """Compute a constant or activation-gated output update. | |
| ``gate_vector`` selects the approximate rank-one update ``(x @ v) * u``. | |
| Otherwise ``coefficient`` selects the constant ``coefficient * u``. A | |
| per-position coefficient tensor may match all leading dimensions of ``x``. | |
| """ | |
| if not torch.is_tensor(x) or x.ndim < 1: | |
| raise ValueError("x must be a tensor with a feature dimension") | |
| if not torch.is_tensor(direction) or direction.ndim != 1: | |
| raise ValueError("direction must be a 1D output vector") | |
| u = direction.to(device=x.device, dtype=torch.float32) | |
| if not torch.isfinite(u).all() or torch.linalg.vector_norm(u) == 0: | |
| raise ValueError("direction must be finite and non-zero") | |
| if gate_vector is not None: | |
| if coefficient is not None: | |
| raise ValueError("provide either gate_vector or coefficient, not both") | |
| if not torch.is_tensor(gate_vector) or gate_vector.ndim != 1: | |
| raise ValueError("gate_vector must be a 1D input vector") | |
| if gate_vector.shape[0] != x.shape[-1]: | |
| raise ValueError("gate_vector width mismatch") | |
| if not torch.isfinite(gate_vector).all(): | |
| raise ValueError("gate_vector must be finite") | |
| gate = F.linear( | |
| x.to(dtype=torch.float32), | |
| gate_vector.to(device=x.device, dtype=torch.float32).unsqueeze(0), | |
| ) | |
| update = gate * u | |
| else: | |
| if coefficient is None: | |
| raise ValueError("a gate_vector or coefficient is required") | |
| gate = torch.as_tensor(coefficient, device=x.device, dtype=torch.float32) | |
| if not torch.isfinite(gate).all(): | |
| raise ValueError("coefficient must be finite") | |
| if gate.ndim == x.ndim - 1: | |
| gate = gate.unsqueeze(-1) | |
| update = gate * u | |
| try: | |
| update = torch.broadcast_to(update, (*x.shape[:-1], u.numel())) | |
| except RuntimeError as exc: | |
| raise ValueError("coefficient shape is not broadcastable to output positions") from exc | |
| return update.to(dtype=x.dtype) | |
| def make_output_hook( | |
| direction: torch.Tensor, | |
| *, | |
| coefficient: float | None = None, | |
| gate_vector: torch.Tensor | None = None, | |
| state: dict | None = None, | |
| ): | |
| """Build a forward hook with controller validation done once at install. | |
| Runtime calls retain Python-side tensor and shape guards, but reuse validated | |
| controller tensors and avoid GPU-to-CPU scalar checks such as ``isfinite`` | |
| and vector-norm reductions on every token. | |
| """ | |
| if (coefficient is None) == (gate_vector is None): | |
| raise ValueError("provide exactly one of coefficient or gate_vector") | |
| if not torch.is_tensor(direction) or direction.ndim != 1: | |
| raise ValueError("direction must be a 1D output vector") | |
| direction = direction.to(dtype=torch.float32) | |
| if not torch.isfinite(direction).all() or torch.linalg.vector_norm(direction) == 0: | |
| raise ValueError("direction must be finite and non-zero") | |
| scale = None | |
| if gate_vector is None: | |
| scale = float(coefficient) | |
| if not math.isfinite(scale): | |
| raise ValueError("coefficient must be finite") | |
| else: | |
| if not torch.is_tensor(gate_vector) or gate_vector.ndim != 1: | |
| raise ValueError("gate_vector must be a 1D input vector") | |
| gate_vector = gate_vector.to(dtype=torch.float32) | |
| if not torch.isfinite(gate_vector).all(): | |
| raise ValueError("gate_vector must be finite") | |
| if state is None: | |
| state = {} | |
| device_cache = {} | |
| constant_dtype_cache = {} | |
| def on_device(device): | |
| key = (device.type, device.index) | |
| if key not in device_cache: | |
| u = direction.to(device=device, dtype=torch.float32) | |
| v = gate_vector.to(device=device, dtype=torch.float32) if gate_vector is not None else None | |
| constant = u * scale if v is None else None | |
| device_cache[key] = (u, v, constant) | |
| return device_cache[key] | |
| def hook(_module, args, output): | |
| if not args: | |
| raise ValueError("down-projection hook received no input") | |
| x = args[0] | |
| if not torch.is_tensor(x) or x.ndim < 1: | |
| raise ValueError("down-projection input must be a tensor with a feature dimension") | |
| target = output[0] if isinstance(output, tuple) else output | |
| if not torch.is_tensor(target): | |
| raise TypeError(f"unsupported hook output type: {type(target)}") | |
| u, v, constant = on_device(x.device) | |
| if target.ndim < 1 or target.shape[-1] != u.numel(): | |
| raise ValueError("output width does not match direction") | |
| if tuple(x.shape[:-1]) != tuple(target.shape[:-1]): | |
| raise ValueError("input and output leading dimensions do not match") | |
| if v is None: | |
| key = (target.device.type, target.device.index, target.dtype, x.dtype) | |
| if key not in constant_dtype_cache: | |
| constant_dtype_cache[key] = constant.to(device=target.device, dtype=x.dtype) | |
| delta = constant_dtype_cache[key].expand(*x.shape[:-1], u.numel()) | |
| else: | |
| if x.shape[-1] != v.numel(): | |
| raise ValueError("input width does not match gate_vector") | |
| gate = F.linear(x.to(dtype=torch.float32), v.unsqueeze(0)) | |
| delta = (gate * u).to(dtype=x.dtype) | |
| if delta.shape != target.shape: | |
| raise ValueError(f"update shape {tuple(delta.shape)} != output shape {tuple(target.shape)}") | |
| state["calls"] = state.get("calls", 0) + 1 | |
| steered = target + delta.to(device=target.device, dtype=target.dtype) | |
| if isinstance(output, tuple): | |
| return (steered, *output[1:]) | |
| return steered | |
| return hook | |
| def install_vllm_hooks(model, specs: Sequence[Mapping]) -> list[dict]: | |
| """Install per-layer constant or rank-one hooks on Qwen-style down projections. | |
| Each spec has ``layer`` and ``direction``, plus exactly one of ``coefficient`` | |
| or ``gate_vector``. This is designed for use inside a trusted | |
| ``LLM.apply_model`` callback; it does not depend on vLLM imports itself. | |
| """ | |
| installed = [] | |
| try: | |
| for spec in specs: | |
| if "layer" not in spec or "direction" not in spec: | |
| raise ValueError("each spec needs a layer and direction") | |
| if ("coefficient" in spec) == ("gate_vector" in spec): | |
| raise ValueError("each spec needs exactly one of coefficient or gate_vector") | |
| layer = int(spec["layer"]) | |
| 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]}") | |
| name, module = matches[0] | |
| if hasattr(module, "_modelclinic_controller_handle"): | |
| raise RuntimeError(f"a ModelClinic controller is already installed on {name}") | |
| device = module.weight.device if hasattr(module, "weight") else None | |
| direction = torch.as_tensor(spec["direction"], device=device, dtype=torch.float32) | |
| state = {"calls": 0} | |
| if "gate_vector" in spec: | |
| gate_vector = torch.as_tensor(spec["gate_vector"], device=device, dtype=torch.float32) | |
| hook = make_output_hook(direction, gate_vector=gate_vector, state=state) | |
| mode = "rank1" | |
| else: | |
| hook = make_output_hook( | |
| direction, coefficient=float(spec["coefficient"]), state=state | |
| ) | |
| mode = "constant" | |
| handle = module.register_forward_hook(hook) | |
| module._modelclinic_controller_handle = handle | |
| module._modelclinic_controller_state = state | |
| installed.append({"module": name, "layer": layer, "mode": mode}) | |
| except Exception: | |
| remove_vllm_hooks(model) | |
| raise | |
| return installed | |
| def read_vllm_hook_stats(model) -> dict: | |
| """Read call counts for installed ModelClinic vLLM hooks.""" | |
| return { | |
| name: dict(module._modelclinic_controller_state) | |
| for name, module in model.named_modules() | |
| if hasattr(module, "_modelclinic_controller_state") | |
| } | |
| def remove_vllm_hooks(model) -> list[str]: | |
| """Remove installed ModelClinic hooks and clear their temporary attributes.""" | |
| removed = [] | |
| for name, module in model.named_modules(): | |
| handle = getattr(module, "_modelclinic_controller_handle", None) | |
| if handle is None: | |
| continue | |
| handle.remove() | |
| delattr(module, "_modelclinic_controller_handle") | |
| delattr(module, "_modelclinic_controller_state") | |
| removed.append(name) | |
| return removed | |