Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion deeptab/configs/models/fttransformer_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,8 @@ class FTTransformerConfig(BaseModelConfig):
head_use_batch_norm : bool, default=False
Whether to use batch normalization in the head layers.
pooling_method : str, default='avg'
Pooling method to be used ('cls', 'avg', etc.).
Pooling method to be used: 'avg', 'max', 'sum', 'last', 'cls', 'learned_flatten',
'attention', 'gated', 'rnn' or 'conv'.
use_cls : bool, default=False
Whether to use a CLS token for pooling.
"""
Expand Down
3 changes: 2 additions & 1 deletion deeptab/configs/models/mambattention_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,8 @@ class MambAttentionConfig(BaseModelConfig):
head_use_batch_norm : bool, default=False
Whether to use batch normalization in the head layers.
pooling_method : str, default='avg'
Pooling method to be used ('avg', 'max', etc.).
Pooling method to be used: 'avg', 'max', 'sum', 'last', 'cls', 'learned_flatten',
'attention', 'gated', 'rnn' or 'conv'.
bidirectional : bool, default=False
Whether to process input sequences bidirectionally.
use_learnable_interaction : bool, default=False
Expand Down
3 changes: 2 additions & 1 deletion deeptab/configs/models/mambular_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,8 @@ class MambularConfig(BaseModelConfig):
head_use_batch_norm : bool, default=False
Whether to use batch normalization in the head layers.
pooling_method : str, default='avg'
Pooling method to use ('avg', 'max', etc.).
Pooling method to be used: 'avg', 'max', 'sum', 'last', 'cls', 'learned_flatten',
'attention', 'gated', 'rnn' or 'conv'.
bidirectional : bool, default=False
Whether to process data bidirectionally.
use_learnable_interaction : bool, default=False
Expand Down
3 changes: 2 additions & 1 deletion deeptab/configs/models/saint_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,8 @@ class SAINTConfig(BaseModelConfig):
head_use_batch_norm : bool, default=False
Whether to use batch normalization in the head layers.
pooling_method : str, default='cls'
Pooling method to be used ('cls', 'avg', etc.).
Pooling method to be used: 'avg', 'max', 'sum', 'last', 'cls', 'learned_flatten',
'attention', 'gated', 'rnn' or 'conv'.
use_cls : bool, default=True
Whether to use a CLS token for pooling.
"""
Expand Down
3 changes: 2 additions & 1 deletion deeptab/configs/models/tabtransformer_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,8 @@ class TabTransformerConfig(BaseModelConfig):
head_use_batch_norm : bool, default=False
Whether to use batch normalization in the head layers.
pooling_method : str, default='avg'
Pooling method to be used ('cls', 'avg', etc.).
Pooling method to be used: 'avg', 'max', 'sum', 'last', 'cls', 'learned_flatten',
'attention', 'gated', 'rnn' or 'conv'.
"""

# Override parent defaults
Expand Down
3 changes: 2 additions & 1 deletion deeptab/configs/models/tabularnn_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,8 @@ class TabulaRNNConfig(BaseModelConfig):
head_use_batch_norm : bool, default=False
Whether to use batch normalization in the head layers.
pooling_method : str, default='avg'
Pooling method to be used ('avg', 'cls', etc.).
Pooling method to be used: 'avg', 'max', 'sum', 'last', 'cls', 'learned_flatten',
'attention', 'gated', 'rnn' or 'conv'.
"""

# Override parent defaults
Expand Down
30 changes: 29 additions & 1 deletion deeptab/core/base_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,25 @@ def initialize_pooling_layers(self, config, n_inputs, hidden_size=None):
)

def pool_sequence(self, out):
"""Pools the sequence dimension based on self.hparams.pooling_method."""
"""Pools the sequence dimension based on self.hparams.pooling_method.

Parameters
----------
out : Tensor
Sequence of shape (batch_size, seq_len, hidden_size).

Returns
-------
Tensor
Pooled tensor of shape (batch_size, hidden_size).

Notes
-----
Supported methods are ``"avg"``, ``"max"``, ``"sum"``, ``"last"``,
``"cls"``, and the learnable ``"learned_flatten"``, ``"attention"``,
``"gated"``, ``"rnn"`` (LSTM output at the last step), and ``"conv"``
(1-D convolution followed by global max pooling).
"""

if self.hparams.pooling_method == "avg":
# Shape: (batch_size, ensemble_size, hidden_size) or (batch_size, hidden_size)
Expand Down Expand Up @@ -238,6 +256,16 @@ def pool_sequence(self, out):
gates = torch.sigmoid(self.gate_layer(out))
out = (out * gates).sum(dim=1) # Shape: (batch_size, hidden_size)
return out
elif self.hparams.pooling_method == "rnn":
# RNN-based pooling: summarize the sequence with the LSTM output
# at the last step. Shape: (batch_size, hidden_size)
out, _ = self.pooling_rnn(out)
return out[:, -1, :]
elif self.hparams.pooling_method == "conv":
# Conv1D over the sequence followed by global max pooling
# Shape: (batch_size, hidden_size, seq_len) -> (batch_size, hidden_size)
out = self.conv1d_pooling(out.transpose(1, 2))
return out.max(dim=2)[0]
else:
raise ValueError(f"Invalid pooling method: {self.hparams.pooling_method}")

Expand Down
44 changes: 44 additions & 0 deletions tests/core/test_base_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,50 @@ def test_tabularnn_n_inputs_is_scalar_and_learned_flatten_works(self):
assert out.shape == (4, 2)


class TestRecurrentAndConvolutionalPooling:
"""The "rnn" and "conv" pooling layers built by initialize_pooling_layers
must also be applied by pool_sequence instead of raising at forward time."""

def test_rnn_pooling_returns_last_lstm_step(self):
from deeptab.architectures.ft_transformer import FTTransformer

config = FTTransformerConfig(d_model=8, n_layers=1, n_heads=2, pooling_method="rnn")
model = FTTransformer(feature_information=(NUM_INFO, {}, {}), config=config)
sequence = torch.randn(4, 3, 8)
expected, _ = model.pooling_rnn(sequence)
torch.testing.assert_close(model.pool_sequence(sequence), expected[:, -1, :])

def test_conv_pooling_returns_global_max_of_convolution(self):
from deeptab.architectures.ft_transformer import FTTransformer

config = FTTransformerConfig(d_model=8, n_layers=1, n_heads=2, pooling_method="conv")
model = FTTransformer(feature_information=(NUM_INFO, {}, {}), config=config)
sequence = torch.randn(4, 3, 8)
expected = model.conv1d_pooling(sequence.transpose(1, 2)).amax(dim=2)
torch.testing.assert_close(model.pool_sequence(sequence), expected)

@pytest.mark.parametrize("pooling_method", ["rnn", "conv"])
@pytest.mark.parametrize(
"architecture_name", ["FTTransformer", "MambAttention", "Mambular", "SAINT", "TabTransformer", "TabulaRNN"]
)
def test_forward_trains_pooling_layer(self, architecture_name, pooling_method):
import deeptab.architectures as architectures
import deeptab.configs as configs

config = getattr(configs, f"{architecture_name}Config")(d_model=8, pooling_method=pooling_method)
for name, value in {"n_layers": 1, "n_heads": 2, "dim_feedforward": 8}.items():
if hasattr(config, name):
setattr(config, name, value)
model = getattr(architectures, architecture_name)(
feature_information=(NUM_INFO, CAT_INFO, {}), num_classes=2, config=config
)
out = model([torch.randn(4, 1)], [torch.randint(0, 5, (4, 1))], [])
assert out.shape == (4, 2)
out.sum().backward()
pooling = model.pooling_rnn if pooling_method == "rnn" else model.conv1d_pooling
assert all(parameter.grad is not None for parameter in pooling.parameters())


class TestEncodingAndClsPooling:
@pytest.mark.parametrize("cls_position", [0, 1])
def test_pooling_respects_embedding_cls_position(self, cls_position):
Expand Down
Loading