-
Notifications
You must be signed in to change notification settings - Fork 3.8k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
LSTMAggregation
#4731
Merged
LSTMAggregation
#4731
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
import pytest | ||
import torch | ||
|
||
from torch_geometric.nn import LSTMAggregation | ||
|
||
|
||
def test_lstm_aggregation(): | ||
x = torch.randn(6, 16) | ||
index = torch.tensor([0, 0, 1, 1, 1, 2]) | ||
|
||
aggr = LSTMAggregation(16, 32) | ||
assert str(aggr) == 'LSTMAggregation(16, 32)' | ||
|
||
aggr.reset_parameters() | ||
|
||
with pytest.raises(ValueError, match="is not sorted"): | ||
aggr(x, torch.tensor([0, 1, 0, 1, 2, 1])) | ||
|
||
out = aggr(x, index) | ||
assert out.size() == (3, 32) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
from typing import Optional | ||
|
||
from torch import Tensor | ||
from torch.nn import LSTM | ||
|
||
from torch_geometric.nn.aggr import Aggregation | ||
from torch_geometric.utils import to_dense_batch | ||
|
||
|
||
class LSTMAggregation(Aggregation): | ||
r"""Performs LSTM-style aggregation in which the elements to aggregate are | ||
interpreted as a sequence. | ||
|
||
.. warn:: | ||
:class:`LSTMAggregation` is not permutation-invariant. | ||
|
||
.. note:: | ||
:class:`LSTMAggregation` requires sorted indices. | ||
|
||
Args: | ||
in_channels (int): Size of each input sample. | ||
out_channels (int): Size of each output sample. | ||
**kwargs (optional): Additional arguments of :class:`torch.nn.LSTM`. | ||
""" | ||
requires_sorted_index = True | ||
|
||
def __init__(self, in_channels: int, out_channels: int, **kwargs): | ||
super().__init__() | ||
self.in_channels = in_channels | ||
self.out_channels = out_channels | ||
self.lstm = LSTM(in_channels, out_channels, batch_first=True, **kwargs) | ||
|
||
def reset_parameters(self): | ||
self.lstm.reset_parameters() | ||
|
||
def forward(self, x: Tensor, index: Optional[Tensor] = None, *, | ||
ptr: Optional[Tensor] = None, dim_size: Optional[int] = None, | ||
dim: int = -2) -> Tensor: | ||
|
||
if index is None: # TODO | ||
raise NotImplementedError(f"'{self.__class__.__name__}' with " | ||
f"'ptr' not yet supported") | ||
|
||
if x.dim() != 2: | ||
raise ValueError(f"'{self.__class__.__name__}' requires " | ||
f"two-dimensional inputs (got '{x.dim()}')") | ||
|
||
if dim not in [-2, 0]: | ||
raise ValueError(f"'{self.__class__.__name__}' needs to perform " | ||
f"aggregation in first dimension (got '{dim}')") | ||
|
||
x, _ = to_dense_batch(x, index, batch_size=dim_size) | ||
return self.lstm(x)[0][:, -1] | ||
|
||
def __repr__(self) -> str: | ||
return (f'{self.__class__.__name__}({self.in_channels}, ' | ||
f'{self.out_channels})') |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Sorry, I am not familiar with LSTM. Some comments: I don't know whether using the output of the last time step is a good idea or not. 1. many padded zeros and fed into LSTM for nodes with smaller degrees. 2. the forgetting issue for long sequences.
How about something like this to remove the effects of padded zeros and average over all the time steps (not sure how it performs):
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think this is a valid point. AFAIK,
GraphSAGE
(and any other LSTM-style aggregation procedure, e.g., Jumping Knowledge), just read out the embeddings after the last element of the sequence has been processed, so I opted to go for this solution. It might be very interesting to explore which reduction performs better here.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Sure, it is worth trying it out later.