From e5b6d5ae54571f6dc7d6e2bdc88db5eb6d7563d4 Mon Sep 17 00:00:00 2001 From: ChrisW09 <50968720+ChrisW09@users.noreply.github.com> Date: Wed, 21 Oct 2026 14:56:34 +0200 Subject: [PATCH 1/2] fix(core): apply rnn and conv pooling in pool_sequence initialize_pooling_layers builds an LSTM for pooling_method="rnn" and a Conv1d for pooling_method="conv", but pool_sequence had no branch for either value and raised "Invalid pooling method" on the first forward pass of every pooling architecture. Use the LSTM output at the last step for "rnn" and the convolution followed by global max pooling for "conv", and list the supported values in the model config docstrings. Fixes #481 --- .../configs/models/fttransformer_config.py | 3 +- .../configs/models/mambattention_config.py | 3 +- deeptab/configs/models/mambular_config.py | 3 +- deeptab/configs/models/saint_config.py | 3 +- .../configs/models/tabtransformer_config.py | 3 +- deeptab/configs/models/tabularnn_config.py | 3 +- deeptab/core/base_model.py | 30 ++++++++++++- tests/core/test_base_model.py | 42 +++++++++++++++++++ 8 files changed, 83 insertions(+), 7 deletions(-) diff --git a/deeptab/configs/models/fttransformer_config.py b/deeptab/configs/models/fttransformer_config.py index 6646b969..ff9b4a46 100644 --- a/deeptab/configs/models/fttransformer_config.py +++ b/deeptab/configs/models/fttransformer_config.py @@ -48,7 +48,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 c816b44e..d4510c75 100644 --- a/deeptab/configs/models/mambattention_config.py +++ b/deeptab/configs/models/mambattention_config.py @@ -69,7 +69,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 1a978c9f..07507a29 100644 --- a/deeptab/configs/models/mambular_config.py +++ b/deeptab/configs/models/mambular_config.py @@ -63,7 +63,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 09eb846d..d9763198 100644 --- a/deeptab/configs/models/tabtransformer_config.py +++ b/deeptab/configs/models/tabtransformer_config.py @@ -48,7 +48,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..236254f9 100644 --- a/tests/core/test_base_model.py +++ b/tests/core/test_base_model.py @@ -117,6 +117,48 @@ 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", "Mambular", "SAINT", "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): From f4275130b8dbccfd075c81d72e9573862dd6e3ce Mon Sep 17 00:00:00 2001 From: ChrisW09 <50968720+ChrisW09@users.noreply.github.com> Date: Wed, 21 Oct 2026 23:54:40 +0200 Subject: [PATCH 2/2] test: run the pooling-training check for all six pooling architectures Refs #481 --- tests/core/test_base_model.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/core/test_base_model.py b/tests/core/test_base_model.py index 236254f9..147bd70b 100644 --- a/tests/core/test_base_model.py +++ b/tests/core/test_base_model.py @@ -140,7 +140,9 @@ def test_conv_pooling_returns_global_max_of_convolution(self): torch.testing.assert_close(model.pool_sequence(sequence), expected) @pytest.mark.parametrize("pooling_method", ["rnn", "conv"]) - @pytest.mark.parametrize("architecture_name", ["FTTransformer", "Mambular", "SAINT", "TabulaRNN"]) + @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