-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathextractor.py
More file actions
315 lines (248 loc) · 10 KB
/
extractor.py
File metadata and controls
315 lines (248 loc) · 10 KB
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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
"""
Capability Extractor module for the UMAF framework.
This module implements the core CapabilityExtractor class that extracts capability fingerprints
from model activations.
"""
from typing import Dict, Any, Optional, Union, List, Tuple
import torch
import torch.nn as nn
import torch.nn.functional as F
from umaf.config import CapabilityExtractorConfig
from umaf.processor import InputProcessor
from umaf.metrics import SimilarityMetric
class TransformerEncoder(nn.Module):
"""
Transformer-based encoder for contextual feature extraction.
Learns complex activation representations through self-attention mechanisms.
"""
def __init__(self, config: CapabilityExtractorConfig):
"""
Initialize transformer encoder.
Args:
config (CapabilityExtractorConfig): Configuration for the encoder
"""
super().__init__()
# Create transformer encoder layers
encoder_layer = nn.TransformerEncoderLayer(
d_model=config.input_dim,
nhead=config.num_heads,
dim_feedforward=config.hidden_dim,
dropout=config.dropout,
batch_first=True
)
# Create transformer encoder
self.encoder = nn.TransformerEncoder(
encoder_layer=encoder_layer,
num_layers=config.num_layers
)
def forward(self, x: torch.Tensor, mask: Optional[torch.Tensor] = None) -> torch.Tensor:
"""
Forward pass through the transformer encoder.
Args:
x (torch.Tensor): Input tensor [batch_size, sequence_length, input_dim]
mask (Optional[torch.Tensor]): Attention mask
Returns:
torch.Tensor: Encoded tensor [batch_size, sequence_length, input_dim]
"""
return self.encoder(x, src_key_padding_mask=mask)
class ProjectionHead(nn.Module):
"""
Projection head for mapping extracted features to a fixed-dimensional latent space.
Produces the final capability fingerprint.
"""
def __init__(self, config: CapabilityExtractorConfig):
"""
Initialize projection head.
Args:
config (CapabilityExtractorConfig): Configuration for the projection head
"""
super().__init__()
# Create projection layers
self.projection = nn.Sequential(
nn.Linear(config.input_dim, config.hidden_dim),
nn.ReLU(),
nn.Dropout(config.dropout),
nn.Linear(config.hidden_dim, config.output_dim)
)
# Optional layer normalization
self.layer_norm = nn.LayerNorm(config.output_dim)
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""
Forward pass through the projection head.
Args:
x (torch.Tensor): Input tensor [batch_size, input_dim]
Returns:
torch.Tensor: Projected tensor [batch_size, output_dim]
"""
x = self.projection(x)
x = self.layer_norm(x)
return x
class CapabilityExtractor(nn.Module):
"""
Main capability extractor module.
Extracts semantically rich, architecture-agnostic model capability fingerprints.
"""
def __init__(
self,
config: CapabilityExtractorConfig = CapabilityExtractorConfig(),
device: Optional[torch.device] = None
):
"""
Initialize capability extractor.
Args:
config (CapabilityExtractorConfig): Configuration for the extractor
device (Optional[torch.device]): Device to use for computation
"""
super().__init__()
self.config = config
self.device = device or torch.device('cuda' if torch.cuda.is_available() else 'cpu')
# Input processor
self.input_processor = InputProcessor(
max_length=config.max_length,
normalization=config.normalization,
device=self.device
)
# Transformer encoder
self.encoder = TransformerEncoder(config)
# Projection head
self.projection_head = ProjectionHead(config)
# Adaptive pooling flag
self.adaptive_pooling = config.adaptive_pooling
# Move to device
self.to(self.device)
def forward(self, activations: torch.Tensor, attention_mask: Optional[torch.Tensor] = None) -> torch.Tensor:
"""
Forward pass through the capability extractor.
Args:
activations (torch.Tensor): Activation tensor [batch_size, sequence_length, input_dim]
attention_mask (Optional[torch.Tensor]): Attention mask [batch_size, sequence_length]
Returns:
torch.Tensor: Capability fingerprint [batch_size, output_dim]
"""
# Validate input dimensions
if activations.size(-1) != self.config.input_dim:
raise ValueError(
f"Expected input dimension {self.config.input_dim}, "
f"got {activations.size(-1)}"
)
# Process input
processed_activations = self.input_processor.process(activations)
# Encode activations
encoded = self.encoder(processed_activations, mask=attention_mask)
# Pool encoded activations
if self.adaptive_pooling:
# Mean pooling over sequence dimension
pooled = encoded.mean(dim=1)
else:
# Use [CLS] token (first token)
pooled = encoded[:, 0]
# Project to fingerprint space
fingerprint = self.projection_head(pooled)
return fingerprint
def extract_fingerprint(
self,
model: Any,
inputs: Dict[str, torch.Tensor],
layer_idx: int = -1
) -> torch.Tensor:
"""
Extract capability fingerprint from a model.
Args:
model (Any): Pre-trained model
inputs (Dict[str, torch.Tensor]): Model inputs
layer_idx (int): Index of the layer to extract activations from (-1 for last layer)
Returns:
torch.Tensor: Capability fingerprint
"""
# Move inputs to device
inputs = {k: v.to(self.device) for k, v in inputs.items()}
# Extract activations
with torch.no_grad():
# Get model outputs
outputs = model(**inputs)
# Extract activations
if hasattr(outputs, 'last_hidden_state'):
activations = outputs.last_hidden_state
elif hasattr(outputs, 'hidden_states'):
activations = outputs.hidden_states[layer_idx]
else:
raise ValueError(
"Model output must have 'last_hidden_state' or 'hidden_states' attribute"
)
# Extract attention mask if available
attention_mask = inputs.get('attention_mask', None)
# Extract fingerprint
return self.forward(activations, attention_mask)
def compute_similarity(
self,
fingerprint1: torch.Tensor,
fingerprint2: torch.Tensor,
metric: Optional[SimilarityMetric] = None
) -> float:
"""
Compute similarity between two fingerprints.
Args:
fingerprint1 (torch.Tensor): First fingerprint
fingerprint2 (torch.Tensor): Second fingerprint
metric (Optional[SimilarityMetric]): Similarity metric to use
Returns:
float: Similarity score
"""
# Use default metric if none provided
metric = metric or self.config.similarity_metric
# Compute similarity
return metric.compute(fingerprint1, fingerprint2)
def is_positive_pair(
self,
task_performance1: float,
task_performance2: float,
fingerprint1: torch.Tensor,
fingerprint2: torch.Tensor
) -> bool:
"""
Determine if two models form a positive pair based on task performance and fingerprint similarity.
Args:
task_performance1 (float): Task performance of first model
task_performance2 (float): Task performance of second model
fingerprint1 (torch.Tensor): Capability fingerprint of first model
fingerprint2 (torch.Tensor): Capability fingerprint of second model
Returns:
bool: True if models form a positive pair, False otherwise
"""
# Compute task performance similarity
task_diff = abs(task_performance1 - task_performance2)
task_sim = 1.0 if task_diff <= 0.05 else 0.0
# Compute representational similarity
rep_sim = self.compute_similarity(fingerprint1, fingerprint2)
# Compute composite similarity score
composite_score = (
self.config.task_weight * task_sim +
self.config.rep_weight * rep_sim
)
# Check if score exceeds threshold
return composite_score > self.config.positive_pair_threshold
def save(self, path: str) -> None:
"""
Save the capability extractor to a file.
Args:
path (str): Path to save the model
"""
torch.save({
'config': self.config,
'state_dict': self.state_dict()
}, path)
@classmethod
def load(cls, path: str, device: Optional[torch.device] = None) -> 'CapabilityExtractor':
"""
Load a capability extractor from a file.
Args:
path (str): Path to load the model from
device (Optional[torch.device]): Device to load the model to
Returns:
CapabilityExtractor: Loaded capability extractor
"""
checkpoint = torch.load(path, map_location=device)
config = checkpoint['config']
extractor = cls(config, device)
extractor.load_state_dict(checkpoint['state_dict'])
return extractor