Comparator Extractor#
extractor
#
| CLASS | DESCRIPTION |
|---|---|
FeatureExtractor |
Extract intermediate features from neural networks using forward hooks. |
| FUNCTION | DESCRIPTION |
|---|---|
extract_features |
Extract features from specified layers of a model. |
Classes#
FeatureExtractor()
#
Extract intermediate features from neural networks using forward hooks.
This class manages PyTorch forward hooks to capture layer features during a forward pass through a neural network. Hooks are automatically cleaned up to prevent memory leaks.
| ATTRIBUTE | DESCRIPTION |
|---|---|
features |
Dictionary mapping layer names to their feature tensors.
TYPE:
|
hooks |
List of registered hook handles.
TYPE:
|
Examples:
Basic usage with sequential model:
>>> import torch
>>> import torch.nn as nn
>>> model = nn.Sequential(nn.Linear(10, 20), nn.ReLU(), nn.Linear(20, 5))
>>> X = torch.randn(100, 10)
>>> extractor = FeatureExtractor()
>>> extractor.register_hooks(model, ["0", "2"])
>>> model(X)
>>> features = extractor.get_features()
>>> extractor.clear()
Using with custom models:
>>> class Net(nn.Module):
... def __init__(self):
... super().__init__()
... self.conv1 = nn.Conv2d(3, 64, 3)
... self.fc = nn.Linear(64, 10)
...
... def forward(self, x):
... x = self.conv1(x)
... return self.fc(x.flatten(1))
>>> model = Net()
>>> extractor = FeatureExtractor()
>>> extractor.register_hooks(model, ["conv1", "fc"])
Notes
Call clear() after extracting features to remove hooks.
| METHOD | DESCRIPTION |
|---|---|
register_hooks |
Register forward hooks on specified layers. |
get_features |
Get extracted features. |
clear |
Remove all registered hooks and clear features. |
Source code in spectre/comparator/extractor.py
Functions#
register_hooks(model: torch.nn.Module, layer_names: list[str]) -> None
#
Register forward hooks on specified layers.
| PARAMETER | DESCRIPTION |
|---|---|
model
|
Model to extract features from.
TYPE:
|
layer_names
|
Names of layers to extract features from.
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If a specified layer name is not found in the model. |
Source code in spectre/comparator/extractor.py
get_features() -> dict[str, torch.Tensor]
#
Get extracted features.
| RETURNS | DESCRIPTION |
|---|---|
dict[str, Tensor]
|
Dictionary mapping layer names to feature tensors. |
Functions#
extract_features(model: torch.nn.Module, X: torch.Tensor, layers: list[str] | None = None, device: torch.device | str | None = None, flatten_conv: bool = True) -> dict[str, torch.Tensor]
#
Extract features from specified layers of a model.
This function uses PyTorch forward hooks to capture intermediate features during a forward pass. Hooks are automatically cleaned up after extraction.
| PARAMETER | DESCRIPTION |
|---|---|
model
|
Model to extract features from. Can be a
TYPE:
|
X
|
Input data, shape (n_samples, ...). Must be compatible with model input.
TYPE:
|
layers
|
Names of layers to extract features from. If None, extract from
all leaf modules (Conv2d, Linear, ReLU, etc.). Layer names follow
PyTorch's
TYPE:
|
device
|
Device to use for computation. If None, use model's device.
TYPE:
|
flatten_conv
|
If True, flatten spatial dimensions of convolutional layer outputs to shape (n_samples, channels * height * width). Useful for comparing convolutional and fully-connected representations.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict[str, Tensor]
|
Dictionary mapping layer names to feature tensors. Each feature has shape (n_samples, ...) depending on layer output. Features are detached from computation graph. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If no layers are found to extract from, or if specified layer names don't exist in the model. |
Examples:
Extract from all layers:
>>> import torch
>>> import torch.nn as nn
>>> model = nn.Sequential(nn.Linear(10, 20), nn.ReLU(), nn.Linear(20, 5))
>>> X = torch.randn(100, 10)
>>> features = extract_features(model, X)
>>> features.keys()
dict_keys(['0', '1', '2'])
>>> features["0"].shape
torch.Size([100, 20])
Extract from specific layers:
>>> features = extract_features(model, X, layers=["0", "2"])
>>> features.keys()
dict_keys(['0', '2'])
With convolutional layers:
>>> conv_model = nn.Sequential(
... nn.Conv2d(3, 64, 3), nn.ReLU(), nn.Flatten(), nn.Linear(64 * 26 * 26, 10)
... )
>>> X_img = torch.randn(32, 3, 28, 28)
>>> features = extract_features(conv_model, X_img, flatten_conv=True)
>>> features["0"].shape # Flattened conv output
torch.Size([32, 43264])
Notes
Temporarily sets the model to eval mode during extraction and restores the original training state afterward. All features are detached from the computation graph to prevent gradient tracking.
Source code in spectre/comparator/extractor.py
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 | |