llmactiv 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- llmactiv/__init__.py +33 -0
- llmactiv/collectors.py +129 -0
- llmactiv/evaluation.py +152 -0
- llmactiv/interventions.py +91 -0
- llmactiv/mask_expressions.py +295 -0
- llmactiv/masks.py +254 -0
- llmactiv/modeling.py +48 -0
- llmactiv-0.1.0.dist-info/METADATA +39 -0
- llmactiv-0.1.0.dist-info/RECORD +11 -0
- llmactiv-0.1.0.dist-info/WHEEL +4 -0
- llmactiv-0.1.0.dist-info/licenses/LICENCE.txt +7 -0
llmactiv/__init__.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
from .masks import (
|
|
2
|
+
NeuronMask, MaskSet, threshold_mask, select_top, select_bottom,
|
|
3
|
+
apply_boolean_mask, combine_masks
|
|
4
|
+
)
|
|
5
|
+
from .mask_expressions import (
|
|
6
|
+
MaskExpressionError, evaluate_mask_expression, parse_mask_expression
|
|
7
|
+
)
|
|
8
|
+
from .collectors import ActivationCollector, ActivationCollectionConfig
|
|
9
|
+
from .interventions import (
|
|
10
|
+
WeightScaleIntervention,
|
|
11
|
+
ActivationShiftIntervention,
|
|
12
|
+
ExponentialSuppressionIntervention,
|
|
13
|
+
Intervention,
|
|
14
|
+
InterventionSession
|
|
15
|
+
)
|
|
16
|
+
from .modeling import ModelBundle, load_model, resolve_mlp_layers
|
|
17
|
+
from .evaluation import (
|
|
18
|
+
next_token, top_next_tokens, generate_text, specific_next_token,
|
|
19
|
+
evaluate_next_token_targets, evaluate_next_tokens
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
__all__ = [
|
|
24
|
+
"NeuronMask", "MaskSet", "threshold_mask", "select_top", "select_bottom",
|
|
25
|
+
"apply_boolean_mask", "combine_masks",
|
|
26
|
+
"MaskExpressionError", "evaluate_mask_expression", "parse_mask_expression",
|
|
27
|
+
"ActivationCollector", "ActivationCollectionConfig",
|
|
28
|
+
"WeightScaleIntervention", "ActivationShiftIntervention",
|
|
29
|
+
"ExponentialSuppressionIntervention", "Intervention", "InterventionSession",
|
|
30
|
+
"ModelBundle", "load_model", "resolve_mlp_layers",
|
|
31
|
+
"next_token", "top_next_tokens", "generate_text", "specific_next_token",
|
|
32
|
+
"evaluate_next_token_targets", "evaluate_next_tokens"
|
|
33
|
+
]
|
llmactiv/collectors.py
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
from dataclasses import dataclass, field
|
|
3
|
+
from typing import Iterable, Sequence
|
|
4
|
+
import torch
|
|
5
|
+
from .masks import NeuronMask, MaskSet
|
|
6
|
+
from .modeling import resolve_mlp_layers
|
|
7
|
+
|
|
8
|
+
@dataclass
|
|
9
|
+
class ActivationCollectionConfig:
|
|
10
|
+
position: str = "last"
|
|
11
|
+
statistic: str = "mean" #w ciągu jednego kontekstu
|
|
12
|
+
aggregate: str = "mean" #pomiędzy kontekstami
|
|
13
|
+
normalize: str = "max"
|
|
14
|
+
layer_indices: Sequence[int] | None = None
|
|
15
|
+
|
|
16
|
+
@dataclass
|
|
17
|
+
class ActivationCollector:
|
|
18
|
+
config: ActivationCollectionConfig = field(default_factory=ActivationCollectionConfig)
|
|
19
|
+
|
|
20
|
+
@torch.inference_mode()
|
|
21
|
+
def collect(self, model, tokenizer, contexts: Iterable[str | tuple[str, str]], *, device=None) -> MaskSet:
|
|
22
|
+
layers = resolve_mlp_layers(model)
|
|
23
|
+
selected = set(self.config.layer_indices) if self.config.layer_indices is not None else set(range(len(layers)))
|
|
24
|
+
totals: dict[int, torch.Tensor] = {}
|
|
25
|
+
extremum: dict[int, torch.Tensor] = {}
|
|
26
|
+
counts = {i: 0 for i in selected}
|
|
27
|
+
handles = []
|
|
28
|
+
|
|
29
|
+
for i, layer in enumerate(layers):
|
|
30
|
+
if i not in selected: continue
|
|
31
|
+
def make_hook(idx):
|
|
32
|
+
def hook(_module, args):
|
|
33
|
+
if not args:
|
|
34
|
+
return
|
|
35
|
+
|
|
36
|
+
x = args[0].detach().float()
|
|
37
|
+
|
|
38
|
+
positional_weights_kind = next(
|
|
39
|
+
(kind for kind in ("linw", "logw", "sqrtw", "squaredw")
|
|
40
|
+
if self.config.statistic.startswith(f"{kind}_")), None)
|
|
41
|
+
positional_statistic = positional_weights_kind is not None
|
|
42
|
+
if positional_statistic:
|
|
43
|
+
x = x.reshape(-1, x.shape[-1])
|
|
44
|
+
elif self.config.position == "last":
|
|
45
|
+
x = x[:, -1, :]
|
|
46
|
+
elif self.config.position == "first":
|
|
47
|
+
x = x[:, 0, :]
|
|
48
|
+
elif self.config.position == "all":
|
|
49
|
+
x = x.reshape(-1, x.shape[-1])
|
|
50
|
+
else:
|
|
51
|
+
raise ValueError(f"Nieobsługiwana pozycja: {self.config.position}")
|
|
52
|
+
|
|
53
|
+
statistic = self.config.statistic[len(positional_weights_kind) + 1:] if positional_statistic else self.config.statistic
|
|
54
|
+
if positional_statistic:
|
|
55
|
+
seq = args[0].detach().float()
|
|
56
|
+
weights = torch.arange(1, seq.shape[1] + 1, device=seq.device, dtype=seq.dtype)
|
|
57
|
+
if positional_weights_kind == "linw":
|
|
58
|
+
positional_weights = weights
|
|
59
|
+
elif positional_weights_kind == "logw":
|
|
60
|
+
positional_weights = weights.log()
|
|
61
|
+
elif positional_weights_kind == "sqrtw":
|
|
62
|
+
positional_weights = weights.sqrt()
|
|
63
|
+
elif positional_weights_kind == "squaredw":
|
|
64
|
+
positional_weights = weights.square()
|
|
65
|
+
else:
|
|
66
|
+
raise ValueError(f"Nieobsługiwana statystyka: {self.config.statistic}")
|
|
67
|
+
if statistic == "mean":
|
|
68
|
+
score = (seq * positional_weights[None, :, None]).sum(dim=1) / positional_weights.sum()
|
|
69
|
+
score = score.mean(dim=0).abs()
|
|
70
|
+
elif statistic == "mean_abs":
|
|
71
|
+
score = (seq.abs() * positional_weights[None, :, None]).sum(dim=1) / positional_weights.sum()
|
|
72
|
+
score = score.mean(dim=0)
|
|
73
|
+
elif statistic == "max":
|
|
74
|
+
score = (seq * positional_weights[None, :, None]).max(dim=1).values.mean(dim=0).abs()
|
|
75
|
+
elif statistic == "max_abs":
|
|
76
|
+
score = (seq.abs() * positional_weights[None, :, None]).max(dim=1).values.mean(dim=0)
|
|
77
|
+
else:
|
|
78
|
+
raise ValueError(f"Nieobsługiwana statystyka: {self.config.statistic}")
|
|
79
|
+
elif statistic == "mean_abs":
|
|
80
|
+
score = x.abs().mean(dim=0)
|
|
81
|
+
elif statistic == "mean":
|
|
82
|
+
score = x.mean(dim=0).abs()
|
|
83
|
+
elif statistic == "max":
|
|
84
|
+
score = x.max(dim=0).values.abs()
|
|
85
|
+
elif statistic == "max_abs":
|
|
86
|
+
score = x.abs().max(dim=0).values
|
|
87
|
+
else:
|
|
88
|
+
raise ValueError(f"Nieobsługiwana statystyka: {self.config.statistic}")
|
|
89
|
+
score = score.cpu()
|
|
90
|
+
if idx not in totals:
|
|
91
|
+
totals[idx] = score.clone()
|
|
92
|
+
extremum[idx] = score.clone()
|
|
93
|
+
else:
|
|
94
|
+
totals[idx] += score
|
|
95
|
+
extremum[idx] = (torch.maximum if self.config.aggregate == "max" else torch.minimum)(extremum[idx], score)
|
|
96
|
+
counts[idx] += 1
|
|
97
|
+
return hook
|
|
98
|
+
handles.append(layer.mlp.down_proj.register_forward_pre_hook(make_hook(i)))
|
|
99
|
+
try:
|
|
100
|
+
for item in contexts:
|
|
101
|
+
prompt = item[0] if isinstance(item, (tuple, list)) else item
|
|
102
|
+
encoded = tokenizer(prompt, return_tensors="pt")
|
|
103
|
+
target_device = device or next(model.parameters()).device
|
|
104
|
+
encoded = {k: v.to(target_device) for k, v in encoded.items()}
|
|
105
|
+
model(**encoded)
|
|
106
|
+
finally:
|
|
107
|
+
for handle in handles: handle.remove()
|
|
108
|
+
masks = {}
|
|
109
|
+
for i in sorted(selected):
|
|
110
|
+
if i not in totals or counts[i] == 0:
|
|
111
|
+
raise RuntimeError(f"Nie zebrano aktywacji dla warstwy {i}.")
|
|
112
|
+
if self.config.aggregate == "mean":
|
|
113
|
+
score = totals[i] / counts[i]
|
|
114
|
+
elif self.config.aggregate == "sum":
|
|
115
|
+
score = totals[i]
|
|
116
|
+
elif self.config.aggregate == "max" or self.config.aggregate == "min":
|
|
117
|
+
score = extremum[i]
|
|
118
|
+
else:
|
|
119
|
+
raise ValueError(f"Nieznana agregacja: {self.config.aggregate}")
|
|
120
|
+
|
|
121
|
+
if self.config.normalize == "max":
|
|
122
|
+
score = score / score.max().clamp_min(1e-12)
|
|
123
|
+
elif self.config.normalize != "none":
|
|
124
|
+
raise ValueError(f"Nieznana normalizacja: {self.config.normalize}")
|
|
125
|
+
masks[i] = NeuronMask(score, i, f"activation_layer_{i}", "numeric", {
|
|
126
|
+
"statistic": self.config.statistic, "position": self.config.position,
|
|
127
|
+
"normalize": self.config.normalize, "context_count": counts[i],
|
|
128
|
+
})
|
|
129
|
+
return MaskSet(masks, "activation_map", {"model_class": type(model).__name__})
|
llmactiv/evaluation.py
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
from typing import Iterable
|
|
3
|
+
import torch
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def _encode(tokenizer, prompt: str, device):
|
|
7
|
+
encoded = tokenizer(prompt, return_tensors="pt")
|
|
8
|
+
return {k: v.to(device) for k, v in encoded.items()}
|
|
9
|
+
|
|
10
|
+
@torch.inference_mode()
|
|
11
|
+
def next_token(model, tokenizer, prompt: str, *, device=None) -> tuple[float, str]:
|
|
12
|
+
device = device or next(model.parameters()).device
|
|
13
|
+
inputs = _encode(tokenizer, prompt, device)
|
|
14
|
+
logits = model(**inputs).logits[0, -1, :].float()
|
|
15
|
+
probs = torch.softmax(logits, dim=-1)
|
|
16
|
+
token_id = int(probs.argmax().item())
|
|
17
|
+
return float(probs[token_id].item()), tokenizer.decode([token_id], skip_special_tokens=False)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@torch.inference_mode()
|
|
21
|
+
def top_next_tokens(model, tokenizer, prompt: str, k: int = 5, *, device=None) -> list[tuple[float, str]]:
|
|
22
|
+
if k <= 0:
|
|
23
|
+
raise ValueError("k <= 0.")
|
|
24
|
+
device = device or next(model.parameters()).device
|
|
25
|
+
inputs = _encode(tokenizer, prompt, device)
|
|
26
|
+
probs = torch.softmax(model(**inputs).logits[0, -1, :].float(), dim=-1)
|
|
27
|
+
top_probabilities, top_ids = torch.topk(probs, min(k, probs.numel()))
|
|
28
|
+
return [
|
|
29
|
+
(float(probability.item()), tokenizer.decode([int(token_id)], skip_special_tokens=False))
|
|
30
|
+
for probability, token_id in zip(top_probabilities, top_ids)
|
|
31
|
+
]
|
|
32
|
+
|
|
33
|
+
@torch.inference_mode()
|
|
34
|
+
def specific_next_token(model, tokenizer, prompt: str, target_text: str, *, device=None) -> tuple[float, str]:
|
|
35
|
+
device = device or next(model.parameters()).device
|
|
36
|
+
inputs = _encode(tokenizer, prompt, device)
|
|
37
|
+
logits = model(**inputs).logits[0, -1, :]
|
|
38
|
+
probs = torch.softmax(logits.float(), dim=-1)
|
|
39
|
+
target_ids = tokenizer.encode(target_text, add_special_tokens=False)
|
|
40
|
+
if not target_ids: return float("nan"), ""
|
|
41
|
+
token_id = target_ids[0]
|
|
42
|
+
return float(probs[token_id].item()), tokenizer.decode([token_id], skip_special_tokens=False)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@torch.inference_mode()
|
|
46
|
+
def evaluate_next_token_targets(model, tokenizer, examples: Iterable[dict], *, device=None) -> list[dict]:
|
|
47
|
+
rows = []
|
|
48
|
+
for example in examples:
|
|
49
|
+
probability, token = specific_next_token(
|
|
50
|
+
model, tokenizer, example["prompt"], example["target"], device=device
|
|
51
|
+
)
|
|
52
|
+
rows.append({**example, "target_first_token": token, "target_first_token_probability": probability})
|
|
53
|
+
return rows
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
@torch.inference_mode()
|
|
57
|
+
def evaluate_next_tokens(model, tokenizer, prompts: Iterable[str], *, device=None) -> list[dict]:
|
|
58
|
+
return [
|
|
59
|
+
{
|
|
60
|
+
"prompt": prompt,
|
|
61
|
+
"predicted_token": token,
|
|
62
|
+
"predicted_token_probability": probability,
|
|
63
|
+
}
|
|
64
|
+
for prompt in prompts
|
|
65
|
+
for probability, token in [next_token(model, tokenizer, prompt, device=device)]
|
|
66
|
+
]
|
|
67
|
+
|
|
68
|
+
@torch.inference_mode()
|
|
69
|
+
def generate_text(
|
|
70
|
+
model, tokenizer, prompt: str, max_new_tokens: int = float("inf"),
|
|
71
|
+
stop_strings: str | Iterable[str] | None = None, stop_token_ids: int | Iterable[int] | None = None,
|
|
72
|
+
temperature: float = 1.0, do_sample: bool = True, top_k: int = 0, top_p: float = 1.0, trace_top_k: int = 5,
|
|
73
|
+
device=None
|
|
74
|
+
) -> tuple[str, list[list[tuple[float, str]]]]:
|
|
75
|
+
|
|
76
|
+
if max_new_tokens < 0:
|
|
77
|
+
raise ValueError("max_new_tokens < 0.")
|
|
78
|
+
if temperature < 0:
|
|
79
|
+
raise ValueError("temperature < 0.")
|
|
80
|
+
if top_k < 0 or trace_top_k <= 0:
|
|
81
|
+
raise ValueError("top_k < 0 or trace_top_k <= 0.")
|
|
82
|
+
if not 0 < top_p <= 1:
|
|
83
|
+
raise ValueError("top_p not in (0, 1].")
|
|
84
|
+
|
|
85
|
+
if stop_strings is None:
|
|
86
|
+
stop_strings = ()
|
|
87
|
+
elif isinstance(stop_strings, str):
|
|
88
|
+
stop_strings = (stop_strings,)
|
|
89
|
+
else:
|
|
90
|
+
stop_strings = tuple(stop_strings)
|
|
91
|
+
if stop_token_ids is None:
|
|
92
|
+
stop_token_ids = set()
|
|
93
|
+
elif isinstance(stop_token_ids, int):
|
|
94
|
+
stop_token_ids = {stop_token_ids}
|
|
95
|
+
else:
|
|
96
|
+
stop_token_ids = set(stop_token_ids)
|
|
97
|
+
|
|
98
|
+
target_device = device or next(model.parameters()).device
|
|
99
|
+
encoded = _encode(tokenizer, prompt, target_device)
|
|
100
|
+
input_ids = encoded["input_ids"]
|
|
101
|
+
generated_ids: list[int] = []
|
|
102
|
+
token_traces: list[list[tuple[float, str]]] = []
|
|
103
|
+
eos_token_id = getattr(tokenizer, "eos_token_id", None)
|
|
104
|
+
|
|
105
|
+
for _ in range(max_new_tokens):
|
|
106
|
+
model_inputs = {**encoded, "input_ids": input_ids}
|
|
107
|
+
logits = model(**model_inputs).logits[0, -1, :].float()
|
|
108
|
+
|
|
109
|
+
if temperature == 0:
|
|
110
|
+
|
|
111
|
+
do_sample = False
|
|
112
|
+
else:
|
|
113
|
+
logits = logits / temperature
|
|
114
|
+
if top_k > 0 and top_k < logits.numel():
|
|
115
|
+
threshold = torch.topk(logits, top_k).values[-1]
|
|
116
|
+
logits[logits < threshold] = -torch.inf
|
|
117
|
+
if top_p < 1.0:
|
|
118
|
+
sorted_logits, sorted_indices = torch.sort(logits, descending=True)
|
|
119
|
+
sorted_probs = torch.softmax(sorted_logits, dim=-1)
|
|
120
|
+
remove = sorted_probs.cumsum(dim=-1) - sorted_probs >= top_p
|
|
121
|
+
sorted_logits[remove] = -torch.inf
|
|
122
|
+
logits.fill_(-torch.inf)
|
|
123
|
+
logits.scatter_(0, sorted_indices, sorted_logits)
|
|
124
|
+
|
|
125
|
+
probabilities = torch.softmax(logits, dim=-1)
|
|
126
|
+
n_trace = min(trace_top_k, probabilities.numel())
|
|
127
|
+
trace_probs, trace_ids = torch.topk(probabilities, n_trace)
|
|
128
|
+
token_traces.append([
|
|
129
|
+
(float(prob.item()), tokenizer.decode([int(token_id)], skip_special_tokens=False))
|
|
130
|
+
for prob, token_id in zip(trace_probs, trace_ids)
|
|
131
|
+
])
|
|
132
|
+
next_id = int(torch.multinomial(probabilities, 1).item()) if do_sample else int(probabilities.argmax().item())
|
|
133
|
+
generated_ids.append(next_id)
|
|
134
|
+
input_ids = torch.cat([input_ids, torch.tensor([[next_id]], device=input_ids.device)], dim=1)
|
|
135
|
+
if "attention_mask" in encoded:
|
|
136
|
+
encoded["attention_mask"] = torch.cat([
|
|
137
|
+
encoded["attention_mask"],
|
|
138
|
+
torch.ones((1, 1), dtype=encoded["attention_mask"].dtype, device=input_ids.device),
|
|
139
|
+
], dim=1)
|
|
140
|
+
|
|
141
|
+
if next_id in stop_token_ids or (eos_token_id is not None and next_id == eos_token_id):
|
|
142
|
+
break
|
|
143
|
+
decoded = tokenizer.decode(generated_ids, skip_special_tokens=False)
|
|
144
|
+
if any(stop and stop in decoded for stop in stop_strings):
|
|
145
|
+
break
|
|
146
|
+
|
|
147
|
+
completion = tokenizer.decode(generated_ids, skip_special_tokens=True)
|
|
148
|
+
if stop_strings:
|
|
149
|
+
stop_positions = [completion.find(stop) for stop in stop_strings if stop and stop in completion]
|
|
150
|
+
if stop_positions:
|
|
151
|
+
completion = completion[:min(stop_positions)]
|
|
152
|
+
return completion, token_traces
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
from abc import ABC, abstractmethod
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from typing import Any
|
|
5
|
+
import torch
|
|
6
|
+
from .masks import MaskSet
|
|
7
|
+
from .modeling import resolve_mlp_layers
|
|
8
|
+
|
|
9
|
+
class Intervention(ABC):
|
|
10
|
+
@abstractmethod
|
|
11
|
+
def apply(self, model: Any, masks: MaskSet, **kwargs) -> Any: ...
|
|
12
|
+
|
|
13
|
+
@dataclass
|
|
14
|
+
class WeightScaleIntervention(Intervention):
|
|
15
|
+
strength: float = 0.1
|
|
16
|
+
|
|
17
|
+
def apply(self, model, masks: MaskSet, **kwargs):
|
|
18
|
+
return _register_activation_interventions(model, masks, scale_fn=lambda values: 1.0 - self.strength * values)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass
|
|
22
|
+
class ActivationShiftIntervention(Intervention):
|
|
23
|
+
strength: float = 0.1
|
|
24
|
+
|
|
25
|
+
def apply(self, model, masks: MaskSet, **kwargs):
|
|
26
|
+
return _register_activation_interventions(model, masks, transform_fn=lambda activation, values: activation - self.strength * values)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass
|
|
30
|
+
class ExponentialSuppressionIntervention(Intervention):
|
|
31
|
+
strength: float = 0.1
|
|
32
|
+
|
|
33
|
+
def apply(self, model, masks: MaskSet, **kwargs):
|
|
34
|
+
return _register_activation_interventions(model, masks, scale_fn=lambda values: torch.exp(-self.strength * values))
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _register_activation_interventions(model, masks, *, scale_fn=None, transform_fn=None):
|
|
38
|
+
layers = resolve_mlp_layers(model)
|
|
39
|
+
handles = []
|
|
40
|
+
for idx, mask in masks.masks.items():
|
|
41
|
+
if idx < 0 or idx >= len(layers):
|
|
42
|
+
raise ValueError(f"Unrecognized layer index {idx}.")
|
|
43
|
+
projection = layers[idx].mlp.down_proj
|
|
44
|
+
values = mask.values.to(device=projection.weight.device, dtype=projection.weight.dtype)
|
|
45
|
+
expected = projection.weight.shape[1]
|
|
46
|
+
if values.numel() != expected:
|
|
47
|
+
raise ValueError(f"Layer {idx}: mask has {values.numel()} elements, but activation requires {expected}.")
|
|
48
|
+
if mask.kind == "boolean":
|
|
49
|
+
values = values.to(projection.weight.dtype)
|
|
50
|
+
scale = scale_fn(values) if scale_fn is not None else None
|
|
51
|
+
if scale is not None and not torch.isfinite(scale).all():
|
|
52
|
+
raise ValueError(f"Layer {idx}: mask creates an invalid scaling factor.")
|
|
53
|
+
|
|
54
|
+
def transform_activation(_module, args, values=values, scale=scale, idx=idx):
|
|
55
|
+
if not args or not isinstance(args[0], torch.Tensor):
|
|
56
|
+
raise TypeError(f"Layer {idx}: no activation tensor found in down_proj input.")
|
|
57
|
+
activation = args[0]
|
|
58
|
+
if activation.shape[-1] != values.numel():
|
|
59
|
+
raise ValueError(
|
|
60
|
+
f"Layer {idx}: activation has shape {activation.shape[-1]}, "
|
|
61
|
+
f"but mask has {values.numel()} elements."
|
|
62
|
+
)
|
|
63
|
+
if transform_fn is not None:
|
|
64
|
+
changed = transform_fn(activation, values.to(device=activation.device, dtype=activation.dtype))
|
|
65
|
+
else:
|
|
66
|
+
changed = activation * scale.to(device=activation.device, dtype=activation.dtype)
|
|
67
|
+
return (changed, *args[1:])
|
|
68
|
+
|
|
69
|
+
handles.append(projection.register_forward_pre_hook(transform_activation))
|
|
70
|
+
return handles
|
|
71
|
+
|
|
72
|
+
@dataclass
|
|
73
|
+
class InterventionSession:
|
|
74
|
+
model: Any
|
|
75
|
+
intervention: Intervention
|
|
76
|
+
masks: MaskSet
|
|
77
|
+
_originals: list[Any] | None = None
|
|
78
|
+
|
|
79
|
+
def __enter__(self):
|
|
80
|
+
self._originals = self.intervention.apply(self.model, self.masks)
|
|
81
|
+
return self.model
|
|
82
|
+
|
|
83
|
+
def restore(self) -> None:
|
|
84
|
+
if self._originals is None: return
|
|
85
|
+
for handle in self._originals:
|
|
86
|
+
handle.remove()
|
|
87
|
+
self._originals = None
|
|
88
|
+
|
|
89
|
+
def __exit__(self, exc_type, exc, tb):
|
|
90
|
+
self.restore()
|
|
91
|
+
return False
|
|
@@ -0,0 +1,295 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
from dataclasses import dataclass
|
|
3
|
+
import re
|
|
4
|
+
from typing import Mapping
|
|
5
|
+
from .masks import MaskSet, NeuronMask, apply_boolean_mask, combine_masks
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
MaskValue = NeuronMask | MaskSet | int | float
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class MaskExpressionError(ValueError):
|
|
12
|
+
pass
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass(frozen=True)
|
|
16
|
+
class _Token:
|
|
17
|
+
kind: str
|
|
18
|
+
value: str
|
|
19
|
+
position: int
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
_TOKEN_RE = re.compile(
|
|
23
|
+
r"(?P<SPACE>\s+)|(?P<STRING>'(?:[^'\\\\]|\\\\.)*'|\"(?:[^\"\\\\]|\\\\.)*\")|"
|
|
24
|
+
r"(?P<NUMBER>(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?)|"
|
|
25
|
+
r"(?P<NAME>[A-Za-z_][A-Za-z0-9_]*)|(?P<OP>\*\*|>=|<=|==|!=|&&|\|\||[+*/(),<>!&|^~%-])"
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _tokenize(text: str) -> list[_Token]:
|
|
30
|
+
tokens = []
|
|
31
|
+
pos = 0
|
|
32
|
+
while pos < len(text):
|
|
33
|
+
match = _TOKEN_RE.match(text, pos)
|
|
34
|
+
if not match:
|
|
35
|
+
raise MaskExpressionError(f"Unexpected character {text[pos]!r} at position {pos}.")
|
|
36
|
+
kind = match.lastgroup
|
|
37
|
+
value = match.group()
|
|
38
|
+
if kind != "SPACE":
|
|
39
|
+
tokens.append(_Token(kind or "", value, pos))
|
|
40
|
+
pos = match.end()
|
|
41
|
+
tokens.append(_Token("EOF", "", len(text)))
|
|
42
|
+
return tokens
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class _Parser:
|
|
46
|
+
|
|
47
|
+
_precedence = {
|
|
48
|
+
"or": 1, "||": 1, "|": 1,
|
|
49
|
+
"and": 2, "&&": 2, "&": 2,
|
|
50
|
+
"xor": 3, "^": 3,
|
|
51
|
+
"==": 4, "!=": 4, ">": 4, ">=": 4, "<": 4, "<=": 4,
|
|
52
|
+
"+": 5, "-": 5,
|
|
53
|
+
"*": 6, "/": 6, "%": 6,
|
|
54
|
+
"**": 7,
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
def __init__(self, text: str):
|
|
58
|
+
self.tokens = _tokenize(text)
|
|
59
|
+
self.index = 0
|
|
60
|
+
|
|
61
|
+
@property
|
|
62
|
+
def current(self) -> _Token:
|
|
63
|
+
return self.tokens[self.index]
|
|
64
|
+
|
|
65
|
+
def take(self) -> _Token:
|
|
66
|
+
token = self.current
|
|
67
|
+
self.index += 1
|
|
68
|
+
return token
|
|
69
|
+
|
|
70
|
+
def parse(self):
|
|
71
|
+
if self.current.kind == "EOF":
|
|
72
|
+
raise MaskExpressionError("Expression cannot be empty.")
|
|
73
|
+
result = self.expression(0)
|
|
74
|
+
if self.current.kind != "EOF":
|
|
75
|
+
raise MaskExpressionError(f"Unexpected token {self.current.value!r} at position {self.current.position}.")
|
|
76
|
+
return result
|
|
77
|
+
|
|
78
|
+
def expression(self, min_precedence: int):
|
|
79
|
+
token = self.take()
|
|
80
|
+
if token.value in {"+", "-", "!", "~"} or (token.kind == "NAME" and token.value.lower() == "not"):
|
|
81
|
+
left = ("unary", token.value.lower(), self.expression(7))
|
|
82
|
+
elif token.value == "(":
|
|
83
|
+
left = self.expression(0)
|
|
84
|
+
self.expect(")")
|
|
85
|
+
elif token.kind == "NUMBER":
|
|
86
|
+
value = float(token.value)
|
|
87
|
+
left = ("number", int(value) if value.is_integer() else value)
|
|
88
|
+
elif token.kind == "STRING":
|
|
89
|
+
left = ("string", token.value[1:-1])
|
|
90
|
+
elif token.kind == "NAME":
|
|
91
|
+
name = token.value
|
|
92
|
+
if name.lower() in {"and", "or", "xor"}:
|
|
93
|
+
raise MaskExpressionError(f"Expected a value before operator {name!r} at position {token.position}.")
|
|
94
|
+
if self.current.value == "(":
|
|
95
|
+
self.take()
|
|
96
|
+
args = []
|
|
97
|
+
if self.current.value != ")":
|
|
98
|
+
while True:
|
|
99
|
+
args.append(self.expression(0))
|
|
100
|
+
if self.current.value != ",":
|
|
101
|
+
break
|
|
102
|
+
self.take()
|
|
103
|
+
self.expect(")")
|
|
104
|
+
left = ("call", name.lower(), args, token.position)
|
|
105
|
+
else:
|
|
106
|
+
left = ("name", name, token.position)
|
|
107
|
+
else:
|
|
108
|
+
raise MaskExpressionError(f"Expected a number, mask name, or '(' at position {token.position}.")
|
|
109
|
+
|
|
110
|
+
while True:
|
|
111
|
+
# Implicit multiplication is limited to number followed by a mask
|
|
112
|
+
# name or parenthesized expression (e.g. 0.2A, 2(A+B)).
|
|
113
|
+
if (left[0] == "number" and
|
|
114
|
+
(self.current.kind == "NAME" or self.current.value == "(")):
|
|
115
|
+
right = self.expression(7)
|
|
116
|
+
left = ("binary", "*", left, right)
|
|
117
|
+
continue
|
|
118
|
+
op = self.current.value.lower()
|
|
119
|
+
precedence = self._precedence.get(op)
|
|
120
|
+
if precedence is None or precedence < min_precedence:
|
|
121
|
+
break
|
|
122
|
+
self.take()
|
|
123
|
+
# Exponentiation is right associative.
|
|
124
|
+
right = self.expression(precedence if op == "**" else precedence + 1)
|
|
125
|
+
left = ("binary", op, left, right)
|
|
126
|
+
return left
|
|
127
|
+
|
|
128
|
+
def expect(self, value: str):
|
|
129
|
+
if self.current.value != value:
|
|
130
|
+
raise MaskExpressionError(f"Expected {value!r} at position {self.current.position}.")
|
|
131
|
+
self.take()
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _eval(node, variables: Mapping[str, MaskValue]):
|
|
135
|
+
tag = node[0]
|
|
136
|
+
if tag == "number":
|
|
137
|
+
return node[1]
|
|
138
|
+
if tag == "string":
|
|
139
|
+
return node[1]
|
|
140
|
+
if tag == "name":
|
|
141
|
+
_, name, position = node
|
|
142
|
+
if name not in variables:
|
|
143
|
+
raise MaskExpressionError(f"Unknown mask {name!r} at position {position}.")
|
|
144
|
+
value = variables[name]
|
|
145
|
+
if not isinstance(value, (NeuronMask, MaskSet, int, float)) or isinstance(value, bool):
|
|
146
|
+
raise MaskExpressionError(f"Variable {name!r} is not a mask or number.")
|
|
147
|
+
return value
|
|
148
|
+
if tag == "unary":
|
|
149
|
+
_, op, child = node
|
|
150
|
+
value = _eval(child, variables)
|
|
151
|
+
if op == "+":
|
|
152
|
+
if not isinstance(value, (int, float)):
|
|
153
|
+
return value
|
|
154
|
+
return value
|
|
155
|
+
if op == "-":
|
|
156
|
+
if isinstance(value, (NeuronMask, MaskSet)):
|
|
157
|
+
return combine_masks(value, -1, "multiply")
|
|
158
|
+
return -value
|
|
159
|
+
if op in {"!", "~", "not"}:
|
|
160
|
+
if isinstance(value, (NeuronMask, MaskSet)):
|
|
161
|
+
return combine_masks(value, None, "not")
|
|
162
|
+
raise MaskExpressionError("Logical negation requires a mask.")
|
|
163
|
+
if tag == "binary":
|
|
164
|
+
_, op, left_node, right_node = node
|
|
165
|
+
left, right = _eval(left_node, variables), _eval(right_node, variables)
|
|
166
|
+
if op in {"+", "-", "*", "/", "**"}:
|
|
167
|
+
operation = {"+": "add", "-": "subtract", "*": "multiply", "/": "divide", "**": "power"}[op]
|
|
168
|
+
if isinstance(left, (NeuronMask, MaskSet)):
|
|
169
|
+
return combine_masks(left, right, operation)
|
|
170
|
+
if isinstance(right, (NeuronMask, MaskSet)):
|
|
171
|
+
if op == "+": return combine_masks(right, left, "add")
|
|
172
|
+
if op == "*": return combine_masks(right, left, "multiply")
|
|
173
|
+
if op == "-": return combine_masks(combine_masks(right, -1, "multiply"), left, "add")
|
|
174
|
+
raise MaskExpressionError(f"Scalar {op} mask is not supported; put the mask on the left.")
|
|
175
|
+
return {"+": lambda: left + right, "-": lambda: left - right,
|
|
176
|
+
"*": lambda: left * right, "/": lambda: left / right,
|
|
177
|
+
"**": lambda: left ** right}[op]()
|
|
178
|
+
if op == "%":
|
|
179
|
+
raise MaskExpressionError("Modulo is not a mask operation.")
|
|
180
|
+
if op in {"&", "&&", "and", "|", "||", "or", "^", "xor"}:
|
|
181
|
+
operation = "and" if op in {"&", "&&", "and"} else "or" if op in {"|", "||", "or"} else "xor"
|
|
182
|
+
return combine_masks(left, right, operation)
|
|
183
|
+
if op in {">", ">=", "<", "<=", "==", "!="}:
|
|
184
|
+
if isinstance(left, (NeuronMask, MaskSet)):
|
|
185
|
+
return _compare(left, right, op)
|
|
186
|
+
if isinstance(right, (NeuronMask, MaskSet)):
|
|
187
|
+
reverse = {">": "<", ">=": "<=", "<": ">", "<=": ">="}.get(op, op)
|
|
188
|
+
return _compare(right, left, reverse)
|
|
189
|
+
return {">": lambda: left > right, ">=": lambda: left >= right,
|
|
190
|
+
"<": lambda: left < right, "<=": lambda: left <= right,
|
|
191
|
+
"==": lambda: left == right, "!=": lambda: left != right}[op]()
|
|
192
|
+
if tag == "call":
|
|
193
|
+
_, name, arg_nodes, position = node
|
|
194
|
+
# Function options like >= and true are bare identifiers, not mask refs.
|
|
195
|
+
args = [_eval(arg, variables) for arg in arg_nodes]
|
|
196
|
+
return _call(name, args, position)
|
|
197
|
+
raise MaskExpressionError("Invalid expression node.")
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def _compare(mask, value, op):
|
|
201
|
+
if isinstance(mask, MaskSet):
|
|
202
|
+
if isinstance(value, MaskSet) and mask.masks.keys() != value.masks.keys():
|
|
203
|
+
raise MaskExpressionError("Compared MaskSets must contain the same layer indices.")
|
|
204
|
+
return MaskSet({i: _compare(m, value.masks[i] if isinstance(value, MaskSet) else value, op)
|
|
205
|
+
for i, m in mask.masks.items()}, f"{mask.name}_compare")
|
|
206
|
+
if not isinstance(mask, NeuronMask) or mask.kind != "numeric":
|
|
207
|
+
raise MaskExpressionError("Comparisons require a numeric mask.")
|
|
208
|
+
if isinstance(value, NeuronMask):
|
|
209
|
+
if value.kind != "numeric" or value.layer_index != mask.layer_index or value.values.shape != mask.values.shape:
|
|
210
|
+
raise MaskExpressionError("Compared masks must be numeric and have the same layer and shape.")
|
|
211
|
+
other = value.values
|
|
212
|
+
elif isinstance(value, (int, float)):
|
|
213
|
+
import torch
|
|
214
|
+
other = mask.values.new_tensor(value)
|
|
215
|
+
else:
|
|
216
|
+
raise MaskExpressionError("Comparison requires a number or mask.")
|
|
217
|
+
result = {">": mask.values > other, ">=": mask.values >= other,
|
|
218
|
+
"<": mask.values < other, "<=": mask.values <= other,
|
|
219
|
+
"==": mask.values == other, "!=": mask.values != other}[op]
|
|
220
|
+
return NeuronMask(result, mask.layer_index, f"{mask.name}_{op}", "boolean", {"operation": "compare", "comparison": op})
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def _call(name: str, args: list, position: int):
|
|
224
|
+
if name in {"min", "max", "mean", "average"}:
|
|
225
|
+
if len(args) < 2:
|
|
226
|
+
raise MaskExpressionError(f"{name}() requires at least two arguments (position {position}).")
|
|
227
|
+
operation = {"min": "min", "max": "max", "mean": "mean", "average": "mean"}[name]
|
|
228
|
+
value = args[0]
|
|
229
|
+
for right in args[1:]:
|
|
230
|
+
if not isinstance(value, (NeuronMask, MaskSet)):
|
|
231
|
+
raise MaskExpressionError(f"{name}() arguments must include a mask.")
|
|
232
|
+
value = combine_masks(value, right, operation)
|
|
233
|
+
return value
|
|
234
|
+
if name in {"not", "invert"}:
|
|
235
|
+
if len(args) != 1 or not isinstance(args[0], (NeuronMask, MaskSet)):
|
|
236
|
+
raise MaskExpressionError(f"{name}() requires exactly one mask (position {position}).")
|
|
237
|
+
return combine_masks(args[0], None, "not")
|
|
238
|
+
if name in {"filter", "mask", "apply_mask"}:
|
|
239
|
+
if len(args) != 2 or not isinstance(args[0], (NeuronMask, MaskSet)) or not isinstance(args[1], (NeuronMask, MaskSet)):
|
|
240
|
+
raise MaskExpressionError(f"{name}() requires a values mask and a selector mask (position {position}).")
|
|
241
|
+
if isinstance(args[0], MaskSet):
|
|
242
|
+
if isinstance(args[1], MaskSet):
|
|
243
|
+
if args[0].masks.keys() != args[1].masks.keys():
|
|
244
|
+
raise MaskExpressionError("MaskSets must contain the same layer indices.")
|
|
245
|
+
rhs = args[1]
|
|
246
|
+
else:
|
|
247
|
+
raise MaskExpressionError("Filtering a MaskSet requires a MaskSet selector.")
|
|
248
|
+
return combine_masks(args[0], rhs, "filter")
|
|
249
|
+
return apply_boolean_mask(args[0], args[1])
|
|
250
|
+
if name in {"top", "bottom"}:
|
|
251
|
+
if len(args) not in (2, 3) or not isinstance(args[0], (NeuronMask, MaskSet)):
|
|
252
|
+
raise MaskExpressionError(f"{name}() syntax: {name}(mask, count_or_percent[, percent]) (position {position}).")
|
|
253
|
+
percent = len(args) == 3 and str(args[2]).lower() in {"true", "percent"}
|
|
254
|
+
amount = args[1]
|
|
255
|
+
if isinstance(amount, bool) or not isinstance(amount, (int, float)):
|
|
256
|
+
raise MaskExpressionError(f"{name}() amount must be a number.")
|
|
257
|
+
def select(mask):
|
|
258
|
+
if not isinstance(mask, NeuronMask):
|
|
259
|
+
raise MaskExpressionError("Selection expects a mask per layer.")
|
|
260
|
+
return mask.select_extremes(amount, descending=name == "top", percent=percent)
|
|
261
|
+
if isinstance(args[0], MaskSet):
|
|
262
|
+
return MaskSet({i: select(m) for i, m in args[0].masks.items()}, f"{args[0].name}_{name}")
|
|
263
|
+
return select(args[0])
|
|
264
|
+
if name in {"threshold", "thresh"}:
|
|
265
|
+
if len(args) not in (2, 3) or not isinstance(args[0], (NeuronMask, MaskSet)):
|
|
266
|
+
raise MaskExpressionError(f"threshold() syntax: threshold(mask, value[, comparison]) (position {position}).")
|
|
267
|
+
comparison = args[2] if len(args) == 3 else ">="
|
|
268
|
+
if comparison not in {">", ">=", "<", "<=", "==", "!="}:
|
|
269
|
+
raise MaskExpressionError("threshold comparison must be one of >, >=, <, <=, ==, !=.")
|
|
270
|
+
def threshold(mask):
|
|
271
|
+
return mask.threshold(args[1], comparison=comparison)
|
|
272
|
+
if isinstance(args[0], MaskSet):
|
|
273
|
+
return MaskSet({i: threshold(m) for i, m in args[0].masks.items()}, f"{args[0].name}_threshold")
|
|
274
|
+
return threshold(args[0])
|
|
275
|
+
raise MaskExpressionError(f"Unknown function {name!r} at position {position}.")
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def evaluate_mask_expression(expression: str, masks: Mapping[str, MaskValue]) -> NeuronMask | MaskSet | float | int:
|
|
279
|
+
|
|
280
|
+
if not isinstance(expression, str):
|
|
281
|
+
raise TypeError("expression must be a string")
|
|
282
|
+
if not isinstance(masks, Mapping):
|
|
283
|
+
raise TypeError("masks must be a mapping of names to masks")
|
|
284
|
+
tree = _Parser(expression).parse()
|
|
285
|
+
try:
|
|
286
|
+
return _eval(tree, masks)
|
|
287
|
+
except MaskExpressionError:
|
|
288
|
+
raise
|
|
289
|
+
except (TypeError, ValueError, ZeroDivisionError) as exc:
|
|
290
|
+
raise MaskExpressionError(str(exc)) from exc
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
parse_mask_expression = evaluate_mask_expression
|
|
294
|
+
|
|
295
|
+
__all__ = ["MaskExpressionError", "evaluate_mask_expression", "parse_mask_expression"]
|
llmactiv/masks.py
ADDED
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
from dataclasses import dataclass, field
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from typing import Literal
|
|
5
|
+
import torch
|
|
6
|
+
|
|
7
|
+
MaskKind = Literal["numeric", "boolean"]
|
|
8
|
+
|
|
9
|
+
@dataclass
|
|
10
|
+
class NeuronMask:
|
|
11
|
+
values: torch.Tensor
|
|
12
|
+
layer_index: int
|
|
13
|
+
name: str = "mask"
|
|
14
|
+
kind: MaskKind = "numeric"
|
|
15
|
+
metadata: dict = field(default_factory=dict)
|
|
16
|
+
|
|
17
|
+
def __post_init__(self) -> None:
|
|
18
|
+
self.values = torch.as_tensor(self.values).detach().cpu()
|
|
19
|
+
if self.values.ndim != 1:
|
|
20
|
+
raise ValueError("Mask must be one-dimensional.")
|
|
21
|
+
if self.kind == "boolean":
|
|
22
|
+
self.values = self.values.bool()
|
|
23
|
+
elif not torch.is_floating_point(self.values):
|
|
24
|
+
self.values = self.values.float()
|
|
25
|
+
if self.kind == "numeric" and not torch.isfinite(self.values).all():
|
|
26
|
+
raise ValueError("Numeric mask contains NaN or infinity.")
|
|
27
|
+
|
|
28
|
+
def clone(self, *, name: str | None = None) -> NeuronMask:
|
|
29
|
+
return NeuronMask(self.values.clone(), self.layer_index, name or self.name, self.kind, dict(self.metadata))
|
|
30
|
+
|
|
31
|
+
def threshold(self, threshold: float, *, comparison: str = ">=",
|
|
32
|
+
inplace: bool = False) -> NeuronMask:
|
|
33
|
+
if self.kind != "numeric":
|
|
34
|
+
raise TypeError("Thresholding requires a numeric mask.")
|
|
35
|
+
if not isinstance(threshold, (int, float)) or not torch.isfinite(torch.tensor(float(threshold))):
|
|
36
|
+
raise ValueError("threshold must be a finite number.")
|
|
37
|
+
if comparison == ">=": values = self.values >= threshold
|
|
38
|
+
elif comparison == ">": values = self.values > threshold
|
|
39
|
+
elif comparison == "<=": values = self.values <= threshold
|
|
40
|
+
elif comparison == "<": values = self.values < threshold
|
|
41
|
+
elif comparison == "==": values = self.values == threshold
|
|
42
|
+
elif comparison == "!=": values = self.values != threshold
|
|
43
|
+
else: raise ValueError("comparison must be one of: >=, >, <=, <, ==, !=")
|
|
44
|
+
if inplace:
|
|
45
|
+
return NeuronMask(self.values.masked_fill(~values, 0), self.layer_index,
|
|
46
|
+
f"{self.name}_thresholded", "numeric",
|
|
47
|
+
{**self.metadata, "threshold": threshold, "comparison": comparison,
|
|
48
|
+
"inplace": True})
|
|
49
|
+
return NeuronMask(values, self.layer_index, f"{self.name}_threshold", "boolean", {**self.metadata, "threshold": threshold, "comparison": comparison})
|
|
50
|
+
|
|
51
|
+
def select_extremes(self, amount: int | float, *, descending: bool = True, percent: bool = False) -> NeuronMask:
|
|
52
|
+
|
|
53
|
+
if self.kind != "numeric":
|
|
54
|
+
raise TypeError("Selecting extremes requires a numeric mask.")
|
|
55
|
+
n = self.values.numel()
|
|
56
|
+
if percent:
|
|
57
|
+
if not isinstance(amount, (int, float)) or not 0 <= amount <= 100:
|
|
58
|
+
raise ValueError("Percent must be a number between 0 and 100.")
|
|
59
|
+
k = int(n * float(amount) / 100)
|
|
60
|
+
else:
|
|
61
|
+
if isinstance(amount, bool) or not isinstance(amount, int) or not 0 <= amount <= n:
|
|
62
|
+
raise ValueError(f"Number of neurons must be an integer between 0 and {n}.")
|
|
63
|
+
k = amount
|
|
64
|
+
order = torch.argsort(self.values, descending=descending, stable=True)
|
|
65
|
+
keep = torch.zeros(n, dtype=torch.bool)
|
|
66
|
+
keep[order[:k]] = True
|
|
67
|
+
direction = "descending" if descending else "ascending"
|
|
68
|
+
return NeuronMask(self.values * keep, self.layer_index,
|
|
69
|
+
f"{self.name}_{direction}_{k}", "numeric",
|
|
70
|
+
{**self.metadata, "selection": direction, "selected_count": k,
|
|
71
|
+
"percent": float(amount) if percent else None})
|
|
72
|
+
|
|
73
|
+
def filter(self, selector: NeuronMask, *, zero_unselected: bool = True, name: str | None = None) -> NeuronMask:
|
|
74
|
+
return apply_boolean_mask(self, selector, zero_unselected=zero_unselected, name=name)
|
|
75
|
+
|
|
76
|
+
def save(self, path: str | Path) -> None:
|
|
77
|
+
payload = {"values": self.values, "layer_index": self.layer_index, "name": self.name,
|
|
78
|
+
"kind": self.kind, "metadata": self.metadata, "format_version": 1}
|
|
79
|
+
torch.save(payload, Path(path))
|
|
80
|
+
|
|
81
|
+
@classmethod
|
|
82
|
+
def load(cls, path: str | Path) -> NeuronMask:
|
|
83
|
+
payload = torch.load(Path(path), map_location="cpu", weights_only=True)
|
|
84
|
+
return cls(payload["values"], int(payload["layer_index"]), payload["name"], payload["kind"], payload.get("metadata", {}))
|
|
85
|
+
|
|
86
|
+
@dataclass
|
|
87
|
+
class MaskSet:
|
|
88
|
+
masks: dict[int, NeuronMask]
|
|
89
|
+
name: str = "mask_set"
|
|
90
|
+
metadata: dict = field(default_factory=dict)
|
|
91
|
+
|
|
92
|
+
def __post_init__(self) -> None:
|
|
93
|
+
for idx, mask in self.masks.items():
|
|
94
|
+
if int(idx) != mask.layer_index:
|
|
95
|
+
raise ValueError(f"Index {idx} does not match mask layer index {mask.layer_index}.")
|
|
96
|
+
|
|
97
|
+
def __getitem__(self, layer_index: int) -> NeuronMask:
|
|
98
|
+
return self.masks[layer_index]
|
|
99
|
+
|
|
100
|
+
def save(self, path: str | Path) -> None:
|
|
101
|
+
torch.save({"masks": {i: {"values": m.values, "layer_index": m.layer_index, "name": m.name,
|
|
102
|
+
"kind": m.kind, "metadata": m.metadata} for i, m in self.masks.items()},
|
|
103
|
+
"name": self.name, "metadata": self.metadata, "format_version": 1}, Path(path))
|
|
104
|
+
|
|
105
|
+
@classmethod
|
|
106
|
+
def load(cls, path: str | Path) -> "MaskSet":
|
|
107
|
+
payload = torch.load(Path(path), map_location="cpu", weights_only=True)
|
|
108
|
+
masks = {int(i): NeuronMask(v["values"], int(v["layer_index"]), v["name"], v["kind"], v.get("metadata", {}))
|
|
109
|
+
for i, v in payload["masks"].items()}
|
|
110
|
+
return cls(masks, payload.get("name", "mask_set"), payload.get("metadata", {}))
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def threshold_mask(mask: NeuronMask, threshold: float, *, comparison: str = ">=",
|
|
114
|
+
inplace: bool = False) -> NeuronMask:
|
|
115
|
+
return mask.threshold(threshold, comparison=comparison, inplace=inplace)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def select_top(mask: NeuronMask, amount: int | float, *, percent: bool = False) -> NeuronMask:
|
|
119
|
+
return mask.select_extremes(amount, descending=True, percent=percent)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def select_bottom(mask: NeuronMask, amount: int | float, *, percent: bool = False) -> NeuronMask:
|
|
123
|
+
return mask.select_extremes(amount, descending=False, percent=percent)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def apply_boolean_mask(values: NeuronMask, selector: NeuronMask, *,
|
|
127
|
+
zero_unselected: bool = True, name: str | None = None) -> NeuronMask:
|
|
128
|
+
if values.kind != "numeric" or selector.kind != "boolean":
|
|
129
|
+
raise TypeError("apply_boolean_mask requires a numeric mask and a boolean mask.")
|
|
130
|
+
if values.layer_index != selector.layer_index or values.values.shape != selector.values.shape:
|
|
131
|
+
raise ValueError("Masks must have the same layer and shape.")
|
|
132
|
+
if not zero_unselected:
|
|
133
|
+
return selector.clone(name=name or selector.name)
|
|
134
|
+
out = values.values.masked_fill(~selector.values, 0)
|
|
135
|
+
return NeuronMask(out, values.layer_index, name or f"{values.name}_filtered_by_{selector.name}",
|
|
136
|
+
"numeric", {"operation": "boolean_filter", "parents": [values.name, selector.name]})
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def combine_masks(left: NeuronMask | MaskSet, right: NeuronMask | MaskSet | float | int | None, operation: str, name: str | None = None) -> NeuronMask | MaskSet:
|
|
140
|
+
aliases = {
|
|
141
|
+
"+": "add",
|
|
142
|
+
"-": "subtract",
|
|
143
|
+
"*": "multiply",
|
|
144
|
+
"/": "divide",
|
|
145
|
+
"**": "power",
|
|
146
|
+
"^": "xor",
|
|
147
|
+
"&&": "and",
|
|
148
|
+
"&": "and",
|
|
149
|
+
"||": "or",
|
|
150
|
+
"|": "or",
|
|
151
|
+
"!=": "not",
|
|
152
|
+
"!": "not",
|
|
153
|
+
"minimum": "min",
|
|
154
|
+
"maximum": "max",
|
|
155
|
+
"average": "mean"
|
|
156
|
+
}
|
|
157
|
+
operation = aliases.get(operation, operation)
|
|
158
|
+
|
|
159
|
+
if isinstance(left, MaskSet):
|
|
160
|
+
if isinstance(right, MaskSet) and left.masks.keys() != right.masks.keys():
|
|
161
|
+
raise ValueError("MaskSets must contain the same layer indices.")
|
|
162
|
+
combined = {
|
|
163
|
+
idx: combine_masks(
|
|
164
|
+
mask,
|
|
165
|
+
right.masks[idx] if isinstance(right, MaskSet) else right,
|
|
166
|
+
operation,
|
|
167
|
+
name=f"{name}_{idx}" if name else None,
|
|
168
|
+
)
|
|
169
|
+
for idx, mask in left.masks.items()
|
|
170
|
+
}
|
|
171
|
+
return MaskSet(combined, name or f"{left.name}_{operation}", {
|
|
172
|
+
**left.metadata,
|
|
173
|
+
"operation": operation,
|
|
174
|
+
"right": right.name if isinstance(right, MaskSet) else right,
|
|
175
|
+
})
|
|
176
|
+
if isinstance(right, MaskSet):
|
|
177
|
+
raise TypeError("Right operand cannot be a MaskSet when left operand is a NeuronMask.")
|
|
178
|
+
|
|
179
|
+
if operation in {"filter", "mask", "apply_mask"}:
|
|
180
|
+
if not isinstance(right, NeuronMask):
|
|
181
|
+
raise TypeError("apply_boolean_mask requires a numeric mask and a boolean mask.")
|
|
182
|
+
return apply_boolean_mask(left, right, name=name)
|
|
183
|
+
|
|
184
|
+
numeric_ops = {"add", "subtract", "multiply", "divide", "power", "min", "max", "mean"}
|
|
185
|
+
logical_ops = {"and", "or", "xor", "not"}
|
|
186
|
+
if operation not in numeric_ops | logical_ops:
|
|
187
|
+
raise ValueError(f"Unknown operation: {operation}")
|
|
188
|
+
|
|
189
|
+
if isinstance(right, NeuronMask):
|
|
190
|
+
if left.layer_index != right.layer_index or left.values.shape != right.values.shape:
|
|
191
|
+
raise ValueError("Masks must have the same layer and shape.")
|
|
192
|
+
b = right.values
|
|
193
|
+
right_name = right.name
|
|
194
|
+
elif isinstance(right, (int, float)):
|
|
195
|
+
b = right
|
|
196
|
+
right_name = str(right)
|
|
197
|
+
elif right is None:
|
|
198
|
+
b = None
|
|
199
|
+
right_name = "None"
|
|
200
|
+
else:
|
|
201
|
+
raise TypeError("Right operand must be a NeuronMask, a number, or None.")
|
|
202
|
+
|
|
203
|
+
a = left.values
|
|
204
|
+
if operation == "not":
|
|
205
|
+
out = ~a.bool()
|
|
206
|
+
kind = "boolean"
|
|
207
|
+
elif operation in logical_ops:
|
|
208
|
+
if not isinstance(right, NeuronMask):
|
|
209
|
+
raise TypeError("Logical operations require two masks.")
|
|
210
|
+
if operation == "and":
|
|
211
|
+
out = a.bool() & b.bool()
|
|
212
|
+
elif operation == "or":
|
|
213
|
+
out = a.bool() | b.bool()
|
|
214
|
+
else:
|
|
215
|
+
out = a.bool() ^ b.bool()
|
|
216
|
+
kind = "boolean"
|
|
217
|
+
else:
|
|
218
|
+
if left.kind != "numeric" or (isinstance(right, NeuronMask) and right.kind != "numeric"):
|
|
219
|
+
raise TypeError("Arithmetic operations require numeric masks.")
|
|
220
|
+
a = a.float()
|
|
221
|
+
if isinstance(b, torch.Tensor):
|
|
222
|
+
b = b.float()
|
|
223
|
+
if operation == "add":
|
|
224
|
+
out = a + b
|
|
225
|
+
elif operation == "subtract":
|
|
226
|
+
out = a - b
|
|
227
|
+
elif operation == "multiply":
|
|
228
|
+
out = a * b
|
|
229
|
+
elif operation == "divide":
|
|
230
|
+
if isinstance(b, torch.Tensor) and torch.any(b == 0):
|
|
231
|
+
raise ZeroDivisionError("Cannot divide mask by zero.")
|
|
232
|
+
if not isinstance(b, torch.Tensor) and b == 0:
|
|
233
|
+
raise ZeroDivisionError("Cannot divide mask by zero.")
|
|
234
|
+
out = a / b
|
|
235
|
+
elif operation == "power":
|
|
236
|
+
out = a ** b
|
|
237
|
+
elif operation == "mean":
|
|
238
|
+
if isinstance(b, torch.Tensor):
|
|
239
|
+
out = (a + b) / 2
|
|
240
|
+
elif operation == "min":
|
|
241
|
+
out = torch.minimum(a, b) if isinstance(b, torch.Tensor) else torch.minimum(a, a.new_tensor(b))
|
|
242
|
+
else:
|
|
243
|
+
out = torch.maximum(a, b) if isinstance(b, torch.Tensor) else torch.maximum(a, a.new_tensor(b))
|
|
244
|
+
if not torch.isfinite(out).all():
|
|
245
|
+
raise ValueError("Operation resulted in NaN or infinity.")
|
|
246
|
+
kind = "numeric"
|
|
247
|
+
|
|
248
|
+
return NeuronMask(
|
|
249
|
+
out,
|
|
250
|
+
left.layer_index,
|
|
251
|
+
name or f"{left.name}_{operation}_{right_name}",
|
|
252
|
+
kind,
|
|
253
|
+
{"operation": operation, "parents": [left.name, right_name]}
|
|
254
|
+
)
|
llmactiv/modeling.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
from dataclasses import dataclass
|
|
3
|
+
from typing import Any
|
|
4
|
+
import torch
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
@dataclass
|
|
8
|
+
class ModelBundle:
|
|
9
|
+
model: Any
|
|
10
|
+
tokenizer: Any
|
|
11
|
+
model_id: str
|
|
12
|
+
|
|
13
|
+
@property
|
|
14
|
+
def device(self) -> torch.device:
|
|
15
|
+
return next(self.model.parameters()).device
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def load_model(model_id: str, *, device: str | None = None,
|
|
19
|
+
torch_dtype: str | torch.dtype = "auto", trust_remote_code: bool = False) -> ModelBundle:
|
|
20
|
+
try:
|
|
21
|
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
|
22
|
+
except ImportError as exc:
|
|
23
|
+
raise ImportError("Import error: failed to import required modules") from exc
|
|
24
|
+
if device is None:
|
|
25
|
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
|
26
|
+
tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=trust_remote_code)
|
|
27
|
+
kwargs: dict[str, Any] = {"torch_dtype": torch_dtype, "trust_remote_code": trust_remote_code}
|
|
28
|
+
if device == "cuda":
|
|
29
|
+
kwargs["device_map"] = "auto"
|
|
30
|
+
model = AutoModelForCausalLM.from_pretrained(model_id, **kwargs)
|
|
31
|
+
if device == "cpu":
|
|
32
|
+
model.to("cpu")
|
|
33
|
+
model.eval()
|
|
34
|
+
return ModelBundle(model=model, tokenizer=tokenizer, model_id=model_id)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def resolve_mlp_layers(model: Any) -> list[Any]:
|
|
38
|
+
candidates = [
|
|
39
|
+
(getattr(getattr(model, "model", None), "layers", None), "model.layers"),
|
|
40
|
+
(getattr(getattr(getattr(model, "model", None), "decoder", None), "layers", None), "model.decoder.layers"),
|
|
41
|
+
(getattr(getattr(model, "transformer", None), "h", None), "transformer.h"),
|
|
42
|
+
]
|
|
43
|
+
for layers, _path in candidates:
|
|
44
|
+
if layers is not None and len(layers) > 0:
|
|
45
|
+
if all(getattr(getattr(layer, "mlp", None), "down_proj", None) is not None for layer in layers):
|
|
46
|
+
return list(layers)
|
|
47
|
+
|
|
48
|
+
raise ValueError("Unknown architecture. Could not find MLP layers with down_proj")
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: llmactiv
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Tools for inspecting and intervening in transformer MLP activations.
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
License-File: LICENCE.txt
|
|
7
|
+
Requires-Python: >=3.11
|
|
8
|
+
Requires-Dist: torch>=2.0
|
|
9
|
+
Requires-Dist: transformers>=5.20.2
|
|
10
|
+
Provides-Extra: dev
|
|
11
|
+
Requires-Dist: build>=1.2; extra == 'dev'
|
|
12
|
+
Requires-Dist: pytest>=8; extra == 'dev'
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
|
|
15
|
+
# biblioteka
|
|
16
|
+
|
|
17
|
+
Biblioteka Python do pracy z maskami neuronów, zbierania aktywacji w warstwach
|
|
18
|
+
MLP, interwencji w modelach transformerowych oraz ewaluacji predykcji.
|
|
19
|
+
|
|
20
|
+
## Wymagania
|
|
21
|
+
|
|
22
|
+
- Python 3.10 lub nowszy.
|
|
23
|
+
- PyTorch 2.0 lub nowszy.
|
|
24
|
+
|
|
25
|
+
## Budowanie dystrybucji
|
|
26
|
+
|
|
27
|
+
Zainstaluj narzędzia budowania, a następnie utwórz wheel i archiwum źródłowe:
|
|
28
|
+
|
|
29
|
+
```powershell
|
|
30
|
+
python -m pip install --upgrade build
|
|
31
|
+
python -m build
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
Pliki `.whl` i `.tar.gz` pojawią się w katalogu `dist/`. Wheel można
|
|
35
|
+
zainstalować lokalnie:
|
|
36
|
+
|
|
37
|
+
```powershell
|
|
38
|
+
python -m pip install <file>.whl
|
|
39
|
+
```
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
llmactiv/__init__.py,sha256=SiYGYCxWRDQc_RxhkReJD-x9FSiA_CW0vwfTqm_mBEI,1307
|
|
2
|
+
llmactiv/collectors.py,sha256=O-eu1AhuyN44bfB8jjETcyWlMtVSIwLRexk5nulSNGA,6782
|
|
3
|
+
llmactiv/evaluation.py,sha256=BJPPvAX9ncH0Mzgx9nGQZS-LZb0I4-vrlenEZF5EBDE,6460
|
|
4
|
+
llmactiv/interventions.py,sha256=sdfw4wMwCXveHx5b5-K654j5A_fK4kmhqoR1csqYb0w,3570
|
|
5
|
+
llmactiv/mask_expressions.py,sha256=aVDqAZdFz9_VIvz-QRK5qiTYbWWxFSjVQ9NJvbE_3w8,13464
|
|
6
|
+
llmactiv/masks.py,sha256=EWOMUd3fd0c7Dp97Gm1KsXhuZdTUL8ONwyS9oEgKswo,11517
|
|
7
|
+
llmactiv/modeling.py,sha256=aRt31ebrm2E6n1c8smInppncS794BZGF_a7oIJgaIiw,1898
|
|
8
|
+
llmactiv-0.1.0.dist-info/METADATA,sha256=pEQFE7BgjNTBwk1pjelW8LCSpqYiAHfIHyiqfAE2-pQ,975
|
|
9
|
+
llmactiv-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
10
|
+
llmactiv-0.1.0.dist-info/licenses/LICENCE.txt,sha256=3OE5ir66BJusAEsE9Wv96iFJfMmCiza--V-Fxgzzwgc,1075
|
|
11
|
+
llmactiv-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
Copyright 2026 Jarosław Strzelczyk
|
|
2
|
+
|
|
3
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
4
|
+
|
|
5
|
+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
|
6
|
+
|
|
7
|
+
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|