internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: pyg-team/pytorch_geometric

Issue:
Broken link in the GNN Cheat sheet
### 📚 Describe the documentation issue

In the cheatsheet [https://pytorch-geometric.readthedocs.io/en/latest/cheatsheet/gnn_cheatsheet.html](https://pytorch-geometric.readthedocs.io/en/latest/cheatsheet/gnn_cheatsheet.html). The paper link for SimpleConv points to a non-existant page. There should not be invalid links on the page.  

[SimpleConv](https://pytorch-geometric.readthedocs.io/en/latest/generated/torch_geometric.nn.conv.SimpleConv.html#torch_geometric.nn.conv.SimpleConv) ([Paper](https://pytorch-geometric.readthedocs.io/en/latest/cheatsheet/None))

### Suggest a potential alternative/fix


I see the code does

```
    not torch_geometric.nn.conv.utils.processes_point_clouds(cls) %}
    * - :class:`~torch_geometric.nn.conv.{{ cls }}` (`Paper <{{ torch_geometric.nn.conv.utils.paper_link(cls) }}>`__)
      - {% if torch_geometric.nn.conv.utils.supports_sparse_tensor(cls) %}✓{% endif %}
      - {% if 
```

If there is a valid appropriate paper - then we should point to that; if not then I suggest having a new document in this repository as the target for this link. The document should describe what SimpleConv does and why there is not paper for it; I assume because it is a very simple example.  




Discussion:

Resolving patch:
diff --git a/torch_geometric/datasets/utils/cheatsheet.py b/torch_geometric/datasets/utils/cheatsheet.py
--- a/torch_geometric/datasets/utils/cheatsheet.py
+++ b/torch_geometric/datasets/utils/cheatsheet.py
@@ -4,7 +4,7 @@
 from typing import Any, List, Optional
 
 
-def paper_link(cls: str) -> str:
+def paper_link(cls: str) -> Optional[str]:
     cls = importlib.import_module('torch_geometric.datasets').__dict__[cls]
     match = re.search('<.+?>', inspect.getdoc(cls), flags=re.DOTALL)
     return None if match is None else match.group().replace('\n', ' ')[1:-1]
diff --git a/torch_geometric/nn/conv/utils/cheatsheet.py b/torch_geometric/nn/conv/utils/cheatsheet.py
--- a/torch_geometric/nn/conv/utils/cheatsheet.py
+++ b/torch_geometric/nn/conv/utils/cheatsheet.py
@@ -1,15 +1,16 @@
 import importlib
 import inspect
 import re
+from typing import Optional
 
 
-def paper_title(cls: str) -> str:
+def paper_title(cls: str) -> Optional[str]:
     cls = importlib.import_module('torch_geometric.nn.conv').__dict__[cls]
     match = re.search('`\".+?\"', inspect.getdoc(cls), flags=re.DOTALL)
     return None if match is None else match.group().replace('\n', ' ')[2:-1]
 
 
-def paper_link(cls: str) -> str:
+def paper_link(cls: str) -> Optional[str]:
     cls = importlib.import_module('torch_geometric.nn.conv').__dict__[cls]
     match = re.search('<.+?>', inspect.getdoc(cls), flags=re.DOTALL)
     return None if match is None else match.group().replace('\n', ' ')[1:-1]


Test patch:
Repository: pyg-team/pytorch_geometric

Issue:
Strange behaviour with the to_dense_adj function
### 🐛 Describe the bug

While using to_dense_adj with edge attributes, I observed that the `idx` values generated are not unique ((line 94 in to_dense_adj.py). As such, the scatter_add function sums up overlapping values and generating an output greater than the original range of edge_attr values.

![image](https://github.com/pyg-team/pytorch_geometric/assets/16525717/be9029d6-f104-4577-bb5a-62c097c1ed9a)

The required tensors can be downloaded from [here](https://filesender.switch.ch/filesender2/download.php?token=d4b1599a-6eee-4b06-8640-be16fb784ab5&files_ids=490595)

Any help or insights are highly appreciated. 

Thanks,
Chinmay

### Environment

* PyG version:2.3.1
* PyTorch version: 2.0.1+cu117
* OS: Ubuntu 20.04
* Python version:3.8.10
* CUDA/cuDNN version:11.7
* How you installed PyTorch and PyG (`conda`, `pip`, source):pip
* Any other relevant information (*e.g.*, version of `torch-scatter`):



Discussion:

Resolving patch:
diff --git a/torch_geometric/utils/to_dense_adj.py b/torch_geometric/utils/to_dense_adj.py
--- a/torch_geometric/utils/to_dense_adj.py
+++ b/torch_geometric/utils/to_dense_adj.py
@@ -23,7 +23,10 @@ def to_dense_adj(
             :math:`\mathbf{b} \in {\{ 0, \ldots, B-1\}}^N`, which assigns each
             node to a specific example. (default: :obj:`None`)
         edge_attr (Tensor, optional): Edge weights or multi-dimensional edge
-            features. (default: :obj:`None`)
+            features.
+            If :obj:`edge_index` contains duplicated edges, the dense adjacency
+            matrix output holds the summed up entries of :obj:`edge_attr` for
+            duplicated edges. (default: :obj:`None`)
         max_num_nodes (int, optional): The size of the output node dimension.
             (default: :obj:`None`)
         batch_size (int, optional) The batch size. (default: :obj:`None`)


Test patch:
Repository: pyg-team/pytorch_geometric

Issue:
Dataset is not undirected
### 🐛 Describe the bug

Dataset is not undirected, despite passing ``to_undirected=True`` flag.

```python
# !pip install pyg-nightly

from torch_geometric.datasets import CitationFull
from torch_geometric.utils import is_undirected

edge_index = CitationFull(root=".", name="Cora_ML", to_undirected=True).edge_index
is_undirected(edge_index)
```
The above outputs: *False*

### Environment

* PyG version: 2.4.0.dev20231010
* PyTorch version: 2.0.1+cu118
* OS: Colab
* Python version: 3.10.12
* CUDA/cuDNN version: 11.8
* How you installed PyTorch and PyG (`conda`, `pip`, source): pip
* Any other relevant information (*e.g.*, version of `torch-scatter`):



Discussion:
Hey ! I ran it on colab and it ran. `is_undirected(edge_index)` is outputing `True`
@emalgorithm I don't see any issue running your code on my side as well. Would you mind trying it again and letting us know how to reproduce it?
You may have the old version stored on disk, so you can try to remove the `processed_dir` and re-process again.

Resolving patch:
diff --git a/torch_geometric/datasets/citation_full.py b/torch_geometric/datasets/citation_full.py
--- a/torch_geometric/datasets/citation_full.py
+++ b/torch_geometric/datasets/citation_full.py
@@ -98,7 +98,8 @@ def raw_file_names(self) -> str:
 
     @property
     def processed_file_names(self) -> str:
-        return 'data.pt'
+        suffix = 'undirected' if self.to_undirected else 'directed'
+        return f'data_{suffix}.pt'
 
     def download(self):
         download_url(self.url.format(self.name), self.raw_dir)


Test patch:
Repository: pyg-team/pytorch_geometric

Issue:
unused `group` parameter in `HGTConv` still documented
### 📚 Describe the documentation issue

#7117 replaces `HGTConv` with the implementation done for the faster `FastHGTConv`. In the process of doing so, the `group` parameter has been removed falling back to the default `sum` operation. (@puririshi98: this was intentional, right?). The docs, however, haven't been updated accordingly.

https://github.com/pyg-team/pytorch_geometric/blob/737707c37fc2bd712a2289b683ec14549926ff49/torch_geometric/nn/conv/hgt_conv.py#L40-L43

### Suggest a potential alternative/fix

Remove the unused parameter from the docs.


Discussion:
Hi, I want to work on this. Assign me.

Resolving patch:
diff --git a/torch_geometric/nn/conv/hgt_conv.py b/torch_geometric/nn/conv/hgt_conv.py
--- a/torch_geometric/nn/conv/hgt_conv.py
+++ b/torch_geometric/nn/conv/hgt_conv.py
@@ -37,10 +37,6 @@ class HGTConv(MessagePassing):
             information.
         heads (int, optional): Number of multi-head-attentions.
             (default: :obj:`1`)
-        group (str, optional): The aggregation scheme to use for grouping node
-            embeddings generated by different relations
-            (:obj:`"sum"`, :obj:`"mean"`, :obj:`"min"`, :obj:`"max"`).
-            (default: :obj:`"sum"`)
         **kwargs (optional): Additional arguments of
             :class:`torch_geometric.nn.conv.MessagePassing`.
     """


Test patch:
Repository: pyg-team/pytorch_geometric

Issue:
Problem with  torch_geometric.transforms
### 🐛 Describe the bug

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
[<ipython-input-20-2b41d296395c>](https://localhost:8080/#) in <cell line: 7>()
      5 import torch.nn as nn
      6 import torch.nn.functional as F
----> 7 import torch_geometric.transforms as T
      8 from tqdm.auto import tqdm
      9 

3 frames
[/usr/local/lib/python3.10/dist-packages/torch_geometric/__init__.py](https://localhost:8080/#) in <module>
----> 1 import torch_geometric.utils
      2 import torch_geometric.data
      3 import torch_geometric.sampler
      4 import torch_geometric.loader
      5 import torch_geometric.transforms

[/usr/local/lib/python3.10/dist-packages/torch_geometric/utils/__init__.py](https://localhost:8080/#) in <module>
      1 import copy
      2 
----> 3 from .scatter import scatter, group_argsort
      4 from .segment import segment
      5 from .sort import index_sort

[/usr/local/lib/python3.10/dist-packages/torch_geometric/utils/scatter.py](https://localhost:8080/#) in <module>
      5 
      6 import torch_geometric.typing
----> 7 from torch_geometric import warnings
      8 from torch_geometric.typing import torch_scatter
      9 from torch_geometric.utils.functions import cumsum

[/usr/local/lib/python3.10/dist-packages/torch_geometric/warnings.py](https://localhost:8080/#) in <module>
      3 import torch_geometric
      4 
----> 5 if torch_geometric.typing.WITH_PT20:  # pragma: no cover
      6     from torch._dynamo import is_compiling as _is_compiling
      7 else:

AttributeError: partially initialized module 'torch_geometric' has no attribute 'typing' (most likely due to a circular import)

### Environment

* PyG version: 2.4.0
* PyTorch version: 2.1.0+cu118
* OS: Windows
* Python version: 3.10.12
* CUDA/cuDNN version:
Cuda compilation tools, release 11.8, V11.8.89
Build cuda_11.8.r11.8/compiler.31833905_0
cuDNN version: 8900
* How you installed PyTorch and PyG (`conda`, `pip`, source): pip
* Any other relevant information (*e.g.*, version of `torch-scatter`):



Discussion:

Resolving patch:
diff --git a/torch_geometric/warnings.py b/torch_geometric/warnings.py
--- a/torch_geometric/warnings.py
+++ b/torch_geometric/warnings.py
@@ -1,13 +1,14 @@
 import warnings
 
+import torch
+
 import torch_geometric
 
-if torch_geometric.typing.WITH_PT20:  # pragma: no cover
-    from torch._dynamo import is_compiling as _is_compiling
-else:
 
-    def _is_compiling() -> bool:  # pragma: no cover
-        return False
+def _is_compiling() -> bool:  # pragma: no cover
+    if torch_geometric.typing.WITH_PT21:
+        return torch._dynamo.is_compiling()
+    return False
 
 
 def warn(message: str):


Test patch:
Repository: pyg-team/pytorch_geometric

Issue:
LatexBuilder for docs fails
### 📚 Describe the documentation issue

The following line makes the docs building crash when using a LatexBuilder

https://github.com/pyg-team/pytorch_geometric/blob/88d7986b6d0a6de5895872270d2ff4fc95fae3b7/docs/source/conf.py#L69C1-L75C43

To reproduce build the docs with the latex builder
```bash
python -m sphinx -T -E -b latex -d _build/doctrees -D language=en . ./build
```

```bash
Extension error:
Handler <function setup.<locals>.rst_jinja_render at 0x1230b4dc0> for event 'source-read' threw an exception (exception: 'LaTeXBuilder' object has no attribute 'templates')

```

### Suggest a potential alternative/fix

_No response_


Discussion:

Resolving patch:
diff --git a/docs/source/conf.py b/docs/source/conf.py
--- a/docs/source/conf.py
+++ b/docs/source/conf.py
@@ -66,10 +66,12 @@
 }
 
 
-def setup(app):
-    def rst_jinja_render(app, _, source):
+def rst_jinja_render(app, _, source):
+    if hasattr(app.builder, 'templates'):
         rst_context = {'torch_geometric': torch_geometric}
         source[0] = app.builder.templates.render_string(source[0], rst_context)
 
+
+def setup(app):
     app.connect('source-read', rst_jinja_render)
     app.add_js_file('js/version_alert.js')


Test patch:
Repository: pyg-team/pytorch_geometric

Issue:
`PCQnm4v2` dataset is regression and `data.y` gives ugly error message, could use a nicer error message
### 🐛 Describe the bug

```
Traceback (most recent call last):
  File "/opt/pyg/pytorch_geometric/x.py", line 195, in <module>
    main()
  File "/opt/pyg/pytorch_geometric/x.py", line 136, in main
    model = GCN(-1, args.emb_dim, args.num_layers, out_channels=train_dataset.num_classes, dropout=args.drop_ratio ).to(device)
  File "/opt/pyg/pytorch_geometric/torch_geometric/data/dataset.py", line 173, in num_classes
    y = torch.cat([data.y for data in data_list if 'y' in data], dim=0)
TypeError: expected Tensor as element 0 in argument 0, but got float
```

code used to repro:
[ondiskdrugdisc.py.zip](https://github.com/pyg-team/pytorch_geometric/files/13573430/ondiskdrugdisc.py.zip)


### Versions

latest stack


Discussion:
This is a regression dataset, so `dataset.num_classes` is expected to fail. We can still print out a better error message though.
oh shoot thanks for lmk, that solves my issue lol, hand't looked too closely into the dataset yet. ill leave this issue about the error message in case this is something you want to change

Resolving patch:
diff --git a/torch_geometric/data/dataset.py b/torch_geometric/data/dataset.py
--- a/torch_geometric/data/dataset.py
+++ b/torch_geometric/data/dataset.py
@@ -158,7 +158,13 @@ def _infer_num_classes(self, y: Optional[Tensor]) -> int:
         elif y.numel() == y.size(0) and not torch.is_floating_point(y):
             return int(y.max()) + 1
         elif y.numel() == y.size(0) and torch.is_floating_point(y):
-            return torch.unique(y).numel()
+            num_classes = torch.unique(y).numel()
+            if num_classes > 2:
+                warnings.warn("Found floating-point labels while calling "
+                              "`dataset.num_classes`. Returning the number of "
+                              "unique elements. Please make sure that this "
+                              "is expected before proceeding.")
+            return num_classes
         else:
             return y.size(-1)
 
@@ -170,7 +176,7 @@ def num_classes(self) -> int:
         # may produce a tuple of data objects (e.g., when used in combination
         # with `RandomLinkSplit`, so we take care of this case here as well:
         data_list = _get_flattened_data_list([data for data in self])
-        y = torch.cat([data.y for data in data_list if 'y' in data], dim=0)
+        y = torch.as_tensor([data.y for data in data_list if 'y' in data])
 
         # Do not fill cache for `InMemoryDataset`:
         if hasattr(self, '_data_list') and self._data_list is not None:


Test patch:
Repository: pyg-team/pytorch_geometric

Issue:
Typo (?) in Aggr.Aggregation's description
### 📚 Describe the documentation issue

First of all, I would like to thank everyone who has helped me in the last weeks to get going with Pytorch-Geometric. I really appreciate it.

There might be a minor typo in the documentation regarding the abstract class `aggr.Aggregation`. 

https://pytorch-geometric.readthedocs.io/en/latest/generated/torch_geometric.nn.aggr.Aggregation.html#torch_geometric.nn.aggr.Aggregation

See second code box:

```python
# Feature matrix holding 10 elements with 64 features each:
x = torch.randn(10, 64)

# Define the boundary indices for three sets:
ptr = torch.tensor([0, 4, 7, 10])

output = aggr(x, ptr=ptr)  #  Output shape: [4, 64]
```


### Suggest a potential alternative/fix

I believe it should be `#  Output shape: [3, 64]` in the last line. It says *three sets* just above. The previous example on indices also has output shape `[3, 64]`.


Discussion:

Resolving patch:
diff --git a/torch_geometric/nn/aggr/base.py b/torch_geometric/nn/aggr/base.py
--- a/torch_geometric/nn/aggr/base.py
+++ b/torch_geometric/nn/aggr/base.py
@@ -47,7 +47,7 @@ class Aggregation(torch.nn.Module):
        # Define the boundary indices for three sets:
        ptr = torch.tensor([0, 4, 7, 10])
 
-       output = aggr(x, ptr=ptr)  #  Output shape: [4, 64]
+       output = aggr(x, ptr=ptr)  #  Output shape: [3, 64]
 
     Note that at least one of :obj:`index` or :obj:`ptr` must be defined.
 


Test patch:
Repository: pyg-team/pytorch_geometric

Issue:
Metapath2vec index out of bounds error
### 🐛 Describe the bug

Hi, I got IndexError: index 1 is out of bounds for dimension 0 with size 1, when running the code below
```
num_nodes_dict = {'a': 2, 'b': 2}
edge_index_dict = {
    ('a', 'to', 'b'): torch.tensor([[0], [0]]),
    ('b', 'to', 'a'): torch.tensor([[0], [0]]),
}
metapath = [('a', 'to', 'b'), ('b', 'to', 'a')]

model = MetaPath2Vec(
    edge_index_dict,
    embedding_dim=16,
    metapath=metapath,
    walk_length=2,
    context_size=2,
    walks_per_node=1,
    num_negative_samples=1,
    num_nodes_dict=num_nodes_dict,
)
loader = model.loader(batch_size=16, shuffle=True)
next(iter(loader))
```

### Versions

Versions of relevant libraries:
[pip3] mypy-extensions==0.4.3
[pip3] numpy==1.23.5
[pip3] torch==2.1.2+cu121
[pip3] torch_geometric==2.5.2
[pip3] torcheval==0.0.7
[pip3] torchvision==0.16.2+cu121
[pip3] triton==2.1.0


Discussion:

Resolving patch:
diff --git a/torch_geometric/datasets/pascal.py b/torch_geometric/datasets/pascal.py
--- a/torch_geometric/datasets/pascal.py
+++ b/torch_geometric/datasets/pascal.py
@@ -192,19 +192,19 @@ def hook(module: torch.nn.Module, x: Tensor, y: Tensor) -> None:
 
             child = obj.getElementsByTagName('xmin')[0].firstChild
             assert child is not None
-            xmin: float = float(child.data)  # type: ignore
+            xmin = int(child.data)  # type: ignore
 
             child = obj.getElementsByTagName('xmax')[0].firstChild
             assert child is not None
-            xmax = float(child.data)  # type: ignore
+            xmax = int(child.data)  # type: ignore
 
             child = obj.getElementsByTagName('ymin')[0].firstChild
             assert child is not None
-            ymin = float(child.data)  # type: ignore
+            ymin = int(child.data)  # type: ignore
 
             child = obj.getElementsByTagName('ymax')[0].firstChild
             assert child is not None
-            ymax = float(child.data)  # type: ignore
+            ymax = int(child.data)  # type: ignore
 
             box = (xmin, ymin, xmax, ymax)
 
diff --git a/torch_geometric/nn/models/metapath2vec.py b/torch_geometric/nn/models/metapath2vec.py
--- a/torch_geometric/nn/models/metapath2vec.py
+++ b/torch_geometric/nn/models/metapath2vec.py
@@ -256,6 +256,7 @@ def sample(rowptr: Tensor, col: Tensor, rowcount: Tensor, subset: Tensor,
     rand = torch.rand((subset.size(0), num_neighbors), device=subset.device)
     rand *= count.to(rand.dtype).view(-1, 1)
     rand = rand.to(torch.long) + rowptr[subset].view(-1, 1)
+    rand = rand.clamp(max=col.numel() - 1)  # If last node is isolated.
 
     col = col[rand] if col.numel() > 0 else rand
     col[mask | (count == 0)] = dummy_idx


Test patch:
Repository: pyg-team/pytorch_geometric

Issue:
Add optional `attr` argument to `BaseData.snapshot` method
### 🛠 Proposed Refactor

The `snapshot` method of a PyG `dataset` currently requires that the temporal attribute data is stored as `dataset.time`.

The [method](https://pytorch-geometric.readthedocs.io/en/latest/generated/torch_geometric.data.Data.html#torch_geometric.data.Data.snapshot) supports both node- and edge-level temporal attributes. However, some datasets may include both node- and edge-level temporal data under distinct keys (e.g., `time` and `edge_time`), and there is currently no way to specify it.

Moreover, the result of `snapshot` when passing a node-level or edge-level data is different; the first returns a `dataset` object with filtered node data only, while the latter returns filtered edge data only, therefore fulfilling different use cases.

In order to avoid having to modify the `dataset.time` object on e.g. datasets with both attributes, PyG should IMHO ideally support receiving an `attr` argument that allows to specify the name of the attribute key in which the data is stored.

### Suggest a potential alternative/fix

See PR #9335.


Discussion:

Resolving patch:
diff --git a/torch_geometric/data/data.py b/torch_geometric/data/data.py
--- a/torch_geometric/data/data.py
+++ b/torch_geometric/data/data.py
@@ -291,13 +291,14 @@ def snapshot(
         self,
         start_time: Union[float, int],
         end_time: Union[float, int],
+        attr: str = 'time',
     ) -> Self:
         r"""Returns a snapshot of :obj:`data` to only hold events that occurred
         in period :obj:`[start_time, end_time]`.
         """
         out = copy.copy(self)
         for store in out.stores:
-            store.snapshot(start_time, end_time)
+            store.snapshot(start_time, end_time, attr)
         return out
 
     def up_to(self, end_time: Union[float, int]) -> Self:
diff --git a/torch_geometric/data/storage.py b/torch_geometric/data/storage.py
--- a/torch_geometric/data/storage.py
+++ b/torch_geometric/data/storage.py
@@ -370,18 +370,20 @@ def snapshot(
         self,
         start_time: Union[float, int],
         end_time: Union[float, int],
+        attr: str = 'time',
     ) -> Self:
-        if 'time' in self:
-            mask = (self.time >= start_time) & (self.time <= end_time)
+        if attr in self:
+            time = self[attr]
+            mask = (time >= start_time) & (time <= end_time)
 
-            if self.is_node_attr('time'):
+            if self.is_node_attr(attr):
                 keys = self.node_attrs()
-            elif self.is_edge_attr('time'):
+            elif self.is_edge_attr(attr):
                 keys = self.edge_attrs()
 
             self._select(keys, mask)
 
-            if self.is_node_attr('time') and 'num_nodes' in self:
+            if self.is_node_attr(attr) and 'num_nodes' in self:
                 self.num_nodes: Optional[int] = int(mask.sum())
 
         return self


Test patch: