Publish interpretune component concept-direction from interpretune/examples@0f1ea3f74af8
Browse filesFiles changed (2)
6 unmodified lines789101112136 unmodified lines2021222324256 unmodified linesfrom __future__ import annotationsfrom collections.abc import Callable, Sequencefrom typing import Any, NamedTupleimport torch6 unmodified linesfrom interpretune.config import AnalysisCfg, init_analysis_cfgsdef embed_pole_pair(module: Any, tokenizer: Any, group_a: Sequence[str], group_b: Sequence[str]) -> torch.Tensor:"""Stack the per-group mean token embeddings of two concept groups into a ``(2, d_model)`` pole pair.6 unmodified lines789101112136 unmodified lines20212223242526272829303132333435363738394041424344454647484950515253546 unmodified linesfrom __future__ import annotationsfrom collections.abc import Callable, Mapping, Sequencefrom typing import Any, NamedTupleimport torch6 unmodified linesfrom interpretune.config import AnalysisCfg, init_analysis_cfgs#: The steering arms' sites, written once as venngram site addresses. The direct arm, the embed-basis patch and the#: direct arm of the scale sweep all edit the unembed's input, a global point that belongs to no block; the J-lens#: validation probes the residual after its fitted layer, which :func:`lens_site_address` names.DIRECT_SITE_ADDRESS = "point:unembed.hook_in"def lens_site_address(layer: int) -> str:"""The venngram site address of the residual stream after block ``layer``: the J-lens validation's probe site.A negative ``layer`` counts from the end of the stack, so ``-1`` names the last block on any depth."""return f"point:hook_resid_post & layers:{layer}"def steering_site(address: Any, n_layers: int, sets: Mapping[str, Any] | None = None) -> str:"""The one hook name a steering arm's venngram site address selects on an ``n_layers``-deep stack.A steering arm edits exactly one site, so an address that selects several (a layer range, a union of points)is refused by name rather than reduced to its first site, which would steer somewhere the address did not say.The point spelling is checked against the activation-point vocabulary, so an unknown point is refused too."""from interpretune.analysis.venngram.sites import resolve_sitessites = resolve_sites(address, n_layers=n_layers, sets=sets).sitesif len(sites) != 1:raise ValueError(f"the steering address {address!r} selects {len(sites)} sites {list(sites)}; an arm edits one")return sites[0]def embed_pole_pair(module: Any, tokenizer: Any, group_a: Sequence[str], group_b: Sequence[str]) -> torch.Tensor:"""Stack the per-group mean token embeddings of two concept groups into a ``(2, d_model)`` pole pair.
104 unmodified lines105106107104 unmodified linesexpected = torch.softmax(pre, dim=-1)assert point.pre_probs == pytest.approx((float(expected[0]), float(expected[1])))assert sum(point.pre_probs) < 1.0104 unmodified lines105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146104 unmodified linesexpected = torch.softmax(pre, dim=-1)assert point.pre_probs == pytest.approx((float(expected[0]), float(expected[1])))assert sum(point.pre_probs) < 1.0# Block depths of the families the steering arms are written for: gemma-2-2b and gemma-3-1b-it (the demos'# substrates), and Llama-3.2-1B and gpt2, two further mapped families the same addresses must serve unchanged._FAMILY_DEPTHS = {"gemma-2-2b": 26, "gemma-3-1b-it": 26, "Llama-3.2-1B": 16, "gpt2": 12}@pytest.mark.parametrize("n_layers", sorted(set(_FAMILY_DEPTHS.values())))def test_direct_site_address_is_the_unembed_input_on_every_depth(n_layers):assert helpers.steering_site(helpers.DIRECT_SITE_ADDRESS, n_layers) == "unembed.hook_in"@pytest.mark.parametrize("family", sorted(_FAMILY_DEPTHS))def test_lens_site_address_names_one_residual_site(family):n_layers = _FAMILY_DEPTHS[family]assert helpers.steering_site(helpers.lens_site_address(n_layers - 2), n_layers) == (f"blocks.{n_layers - 2}.hook_resid_post")# The last block by a negative index, which the interp-engine arm uses in place of the unembed's input.assert helpers.steering_site(helpers.lens_site_address(-1), n_layers) == f"blocks.{n_layers - 1}.hook_resid_post"def test_steering_site_refuses_an_address_selecting_several_sites():with pytest.raises(ValueError, match=r"selects 4 sites .*an arm edits one"):helpers.steering_site("point:hook_resid_post & layers:8:12", 12)def test_steering_site_refuses_an_unknown_point_by_name():from interpretune.utils import MisconfigurationExceptionwith pytest.raises(MisconfigurationException, match=r"not an activation point"):helpers.steering_site("point:hook_resid_sideways", 12)def test_steering_site_refuses_a_layer_past_the_stack():from interpretune.utils import MisconfigurationExceptionwith pytest.raises(MisconfigurationException, match=r"Layer 24 is outside a stack of 16 blocks"):helpers.steering_site(helpers.lens_site_address(24), 16)
steering_demo_helpers.py+30-1
tests/test_steering_demo_helpers.py+39