diff --git a/deeptab/configs/models/fttransformer_config.py b/deeptab/configs/models/fttransformer_config.py index e08559a6..1cff591c 100644 --- a/deeptab/configs/models/fttransformer_config.py +++ b/deeptab/configs/models/fttransformer_config.py @@ -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. """ diff --git a/deeptab/configs/models/mambattention_config.py b/deeptab/configs/models/mambattention_config.py index 123acb90..671afebb 100644 --- a/deeptab/configs/models/mambattention_config.py +++ b/deeptab/configs/models/mambattention_config.py @@ -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 diff --git a/deeptab/configs/models/mambular_config.py b/deeptab/configs/models/mambular_config.py index 39fd2605..23164b10 100644 --- a/deeptab/configs/models/mambular_config.py +++ b/deeptab/configs/models/mambular_config.py @@ -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 diff --git a/deeptab/configs/models/saint_config.py b/deeptab/configs/models/saint_config.py index bd8f538e..ee79758d 100644 --- a/deeptab/configs/models/saint_config.py +++ b/deeptab/configs/models/saint_config.py @@ -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. """ diff --git a/deeptab/configs/models/tabtransformer_config.py b/deeptab/configs/models/tabtransformer_config.py index e4fd0c05..e1318c92 100644 --- a/deeptab/configs/models/tabtransformer_config.py +++ b/deeptab/configs/models/tabtransformer_config.py @@ -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 diff --git a/deeptab/configs/models/tabularnn_config.py b/deeptab/configs/models/tabularnn_config.py index 2e480d82..251ddbd6 100644 --- a/deeptab/configs/models/tabularnn_config.py +++ b/deeptab/configs/models/tabularnn_config.py @@ -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 diff --git a/deeptab/core/base_model.py b/deeptab/core/base_model.py index 9567ae49..594a68ee 100644 --- a/deeptab/core/base_model.py +++ b/deeptab/core/base_model.py @@ -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) @@ -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}") diff --git a/tests/core/test_base_model.py b/tests/core/test_base_model.py index 690d0ace..147bd70b 100644 --- a/tests/core/test_base_model.py +++ b/tests/core/test_base_model.py @@ -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):