adapters
shrinkai.adapters
Model-agnostic adapters bridging teacher/student architectures for distillation.
FeatureExtractor wraps any nn.Module to capture intermediate activations via
forward hooks, without modifying the model's source code. FeatureProjector and
AttentionHeadSelector then reconcile dimension mismatches between a teacher's
and a student's internal representations (channel counts, attention head
counts, ...) so that feature-based losses (shrinkai.distillation.losses) can
compare them directly.
Modules:
| Name | Description |
|---|---|
extractor |
|
projector |
|
Classes:
| Name | Description |
|---|---|
AttentionHeadSelector |
Adapts teacher attention maps to match student dimensions by selecting specific heads. |
FeatureExtractor |
Wraps a PyTorch model to extract intermediate feature maps via forward hooks. |
FeatureProjector |
Projects student features to match the channel dimensions of the teacher features. |
Classes
AttentionHeadSelector
Bases: Module
Adapts teacher attention maps to match student dimensions by selecting specific heads.
In Transformer distillation (e.g., TinyBERT), a student often has fewer attention heads than the teacher (e.g., 2 vs 12). This adapter slices the teacher's attention tensors [Batch, Heads, Seq, Seq] to keep only the indices corresponding to the student.
Methods:
| Name | Description |
|---|---|
__init__ |
Initializes the AttentionHeadSelector. |
forward |
Slices the attention tensors along the head dimension. |
Source code in src/shrinkai/adapters/projector.py
Methods:
__init__
Initializes the AttentionHeadSelector.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
heads_to_keep
|
list[int]
|
List of integer indices representing which teacher heads to retain (e.g., [0, 6] to keep the first and seventh head). |
required |
Source code in src/shrinkai/adapters/projector.py
forward
Slices the attention tensors along the head dimension.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
attention_dict
|
dict[str, Tensor]
|
Dictionary of attention tensors of shape [B, Num_Heads, S, S]. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
dict[str, torch.Tensor]: Dictionary of sliced tensors of shape [B, len(heads_to_keep), S, S]. |
Source code in src/shrinkai/adapters/projector.py
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. |
Source code in src/shrinkai/adapters/extractor.py
remove_hooks
FeatureProjector
Bases: Module
Projects student features to match the channel dimensions of the teacher features.
Uses 1x1 convolutions for spatial feature maps (B, C, H, W) or Linear layers for flattened features (B, C) or sequences (B, L, D).
Methods:
| Name | Description |
|---|---|
__init__ |
Initializes the FeatureProjector. |
forward |
Applies the projection layers to the student's extracted features. |
Source code in src/shrinkai/adapters/projector.py
Methods:
__init__
Initializes the FeatureProjector.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mapping_config
|
dict[str, dict[str, Any]]
|
A dictionary defining the projection parameters for each layer.
Format: {
"block_1": {"in_channels": 64, "out_channels": 128, "type": "conv", "use_norm": True},
"block_2": {"in_channels": 256, "out_channels": 512, "type": "linear"}
}
- |
required |
Source code in src/shrinkai/adapters/projector.py
forward
Applies the projection layers to the student's extracted features.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
student_features
|
dict[str, Tensor]
|
Dictionary of raw feature tensors from the student. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
dict[str, torch.Tensor]: Dictionary of projected feature tensors. |