projector
shrinkai.adapters.projector
Classes:
| Name | Description |
|---|---|
AttentionHeadSelector |
Adapts teacher attention maps to match student dimensions by selecting specific heads. |
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
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. |