extractor
shrinkai.adapters.extractor
Classes:
| Name | Description |
|---|---|
FeatureExtractor |
Wraps a PyTorch model to extract intermediate feature maps via forward hooks. |
Classes
FeatureExtractor
Bases: Module
Wraps a PyTorch model to extract intermediate feature maps via forward hooks.
This wrapper does not modify the original model's source code. It dynamically attaches hooks to intercept the output of specified layers during the forward pass.
Methods:
| Name | Description |
|---|---|
__init__ |
Initializes the FeatureExtractor. |
forward |
Performs a forward pass and captures intermediate features. |
remove_hooks |
Removes all registered hooks to prevent memory leaks. |
Source code in src/shrinkai/adapters/extractor.py
Methods:
__init__
Initializes the FeatureExtractor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Module
|
The PyTorch model to extract features from. |
required |
target_layers
|
Iterable[str] | Mapping[str, str]
|
An iterable of layer names to hook (e.g., ["layer1", "layer2"]), or a mapping dictionary to assign common aliases for cross-model matching (e.g., {"layer4.conv1": "block_1", "layer8.conv1": "block_2"}). |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a target layer does not exist in the model. |
Source code in src/shrinkai/adapters/extractor.py
forward
Performs a forward pass and captures intermediate features.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Tensor
|
Input tensor. |
required |
*args
|
Any
|
Additional positional arguments for the model. |
()
|
**kwargs
|
Any
|
Additional keyword arguments for the model. |
{}
|
Returns:
| Type | Description |
|---|---|
tuple[Tensor, dict[str, Tensor]]
|
tuple[torch.Tensor, dict[str, torch.Tensor]]: A tuple containing the final model output (logits) and a dictionary of extracted features. |