pyg-nightly 2.6.0.dev20240704__py3-none-any.whl → 2.8.0.dev20251207__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of pyg-nightly might be problematic. Click here for more details.
- {pyg_nightly-2.6.0.dev20240704.dist-info → pyg_nightly-2.8.0.dev20251207.dist-info}/METADATA +81 -58
- {pyg_nightly-2.6.0.dev20240704.dist-info → pyg_nightly-2.8.0.dev20251207.dist-info}/RECORD +265 -221
- {pyg_nightly-2.6.0.dev20240704.dist-info → pyg_nightly-2.8.0.dev20251207.dist-info}/WHEEL +1 -1
- pyg_nightly-2.8.0.dev20251207.dist-info/licenses/LICENSE +19 -0
- torch_geometric/__init__.py +34 -1
- torch_geometric/_compile.py +11 -3
- torch_geometric/_onnx.py +228 -0
- torch_geometric/config_mixin.py +8 -3
- torch_geometric/config_store.py +1 -1
- torch_geometric/contrib/__init__.py +1 -1
- torch_geometric/contrib/explain/pgm_explainer.py +1 -1
- torch_geometric/data/__init__.py +19 -1
- torch_geometric/data/batch.py +2 -2
- torch_geometric/data/collate.py +1 -3
- torch_geometric/data/data.py +110 -6
- torch_geometric/data/database.py +19 -5
- torch_geometric/data/dataset.py +14 -9
- torch_geometric/data/extract.py +1 -1
- torch_geometric/data/feature_store.py +17 -22
- torch_geometric/data/graph_store.py +3 -2
- torch_geometric/data/hetero_data.py +139 -7
- torch_geometric/data/hypergraph_data.py +2 -2
- torch_geometric/data/in_memory_dataset.py +2 -2
- torch_geometric/data/lightning/datamodule.py +42 -28
- torch_geometric/data/storage.py +9 -1
- torch_geometric/datasets/__init__.py +20 -1
- torch_geometric/datasets/actor.py +7 -9
- torch_geometric/datasets/airfrans.py +17 -20
- torch_geometric/datasets/airports.py +8 -10
- torch_geometric/datasets/amazon.py +8 -11
- torch_geometric/datasets/amazon_book.py +8 -9
- torch_geometric/datasets/amazon_products.py +7 -9
- torch_geometric/datasets/aminer.py +8 -9
- torch_geometric/datasets/aqsol.py +10 -13
- torch_geometric/datasets/attributed_graph_dataset.py +8 -10
- torch_geometric/datasets/ba_multi_shapes.py +10 -12
- torch_geometric/datasets/ba_shapes.py +5 -6
- torch_geometric/datasets/brca_tgca.py +1 -1
- torch_geometric/datasets/city.py +157 -0
- torch_geometric/datasets/dbp15k.py +1 -1
- torch_geometric/datasets/gdelt_lite.py +3 -2
- torch_geometric/datasets/ged_dataset.py +3 -2
- torch_geometric/datasets/git_mol_dataset.py +263 -0
- torch_geometric/datasets/gnn_benchmark_dataset.py +3 -2
- torch_geometric/datasets/hgb_dataset.py +2 -2
- torch_geometric/datasets/hm.py +1 -1
- torch_geometric/datasets/instruct_mol_dataset.py +134 -0
- torch_geometric/datasets/linkx_dataset.py +4 -3
- torch_geometric/datasets/lrgb.py +3 -5
- torch_geometric/datasets/malnet_tiny.py +2 -1
- torch_geometric/datasets/md17.py +3 -3
- torch_geometric/datasets/medshapenet.py +145 -0
- torch_geometric/datasets/mnist_superpixels.py +2 -3
- torch_geometric/datasets/modelnet.py +1 -1
- torch_geometric/datasets/molecule_gpt_dataset.py +492 -0
- torch_geometric/datasets/molecule_net.py +3 -2
- torch_geometric/datasets/neurograph.py +1 -3
- torch_geometric/datasets/ogb_mag.py +1 -1
- torch_geometric/datasets/opf.py +19 -5
- torch_geometric/datasets/pascal_pf.py +1 -1
- torch_geometric/datasets/pcqm4m.py +2 -1
- torch_geometric/datasets/ppi.py +2 -1
- torch_geometric/datasets/protein_mpnn_dataset.py +451 -0
- torch_geometric/datasets/qm7.py +1 -1
- torch_geometric/datasets/qm9.py +3 -2
- torch_geometric/datasets/shrec2016.py +2 -2
- torch_geometric/datasets/snap_dataset.py +8 -4
- torch_geometric/datasets/tag_dataset.py +462 -0
- torch_geometric/datasets/teeth3ds.py +269 -0
- torch_geometric/datasets/web_qsp_dataset.py +342 -0
- torch_geometric/datasets/wikics.py +2 -1
- torch_geometric/datasets/wikidata.py +2 -1
- torch_geometric/deprecation.py +1 -1
- torch_geometric/distributed/__init__.py +13 -0
- torch_geometric/distributed/dist_loader.py +2 -2
- torch_geometric/distributed/local_feature_store.py +3 -2
- torch_geometric/distributed/local_graph_store.py +2 -1
- torch_geometric/distributed/partition.py +9 -8
- torch_geometric/distributed/rpc.py +3 -3
- torch_geometric/edge_index.py +35 -22
- torch_geometric/explain/algorithm/attention_explainer.py +219 -29
- torch_geometric/explain/algorithm/base.py +2 -2
- torch_geometric/explain/algorithm/captum.py +1 -1
- torch_geometric/explain/algorithm/captum_explainer.py +2 -1
- torch_geometric/explain/algorithm/gnn_explainer.py +406 -69
- torch_geometric/explain/algorithm/graphmask_explainer.py +8 -8
- torch_geometric/explain/algorithm/pg_explainer.py +305 -47
- torch_geometric/explain/explainer.py +2 -2
- torch_geometric/explain/explanation.py +89 -5
- torch_geometric/explain/metric/faithfulness.py +1 -1
- torch_geometric/graphgym/checkpoint.py +2 -1
- torch_geometric/graphgym/config.py +3 -2
- torch_geometric/graphgym/imports.py +15 -4
- torch_geometric/graphgym/logger.py +1 -1
- torch_geometric/graphgym/loss.py +1 -1
- torch_geometric/graphgym/models/encoder.py +2 -2
- torch_geometric/graphgym/models/layer.py +1 -1
- torch_geometric/graphgym/utils/comp_budget.py +4 -3
- torch_geometric/hash_tensor.py +798 -0
- torch_geometric/index.py +16 -7
- torch_geometric/inspector.py +6 -2
- torch_geometric/io/fs.py +27 -0
- torch_geometric/io/tu.py +2 -3
- torch_geometric/llm/__init__.py +9 -0
- torch_geometric/llm/large_graph_indexer.py +741 -0
- torch_geometric/llm/models/__init__.py +23 -0
- torch_geometric/llm/models/g_retriever.py +251 -0
- torch_geometric/llm/models/git_mol.py +336 -0
- torch_geometric/llm/models/glem.py +397 -0
- torch_geometric/llm/models/llm.py +470 -0
- torch_geometric/llm/models/llm_judge.py +158 -0
- torch_geometric/llm/models/molecule_gpt.py +222 -0
- torch_geometric/llm/models/protein_mpnn.py +333 -0
- torch_geometric/llm/models/sentence_transformer.py +188 -0
- torch_geometric/llm/models/txt2kg.py +353 -0
- torch_geometric/llm/models/vision_transformer.py +38 -0
- torch_geometric/llm/rag_loader.py +154 -0
- torch_geometric/llm/utils/__init__.py +10 -0
- torch_geometric/llm/utils/backend_utils.py +443 -0
- torch_geometric/llm/utils/feature_store.py +169 -0
- torch_geometric/llm/utils/graph_store.py +199 -0
- torch_geometric/llm/utils/vectorrag.py +125 -0
- torch_geometric/loader/cluster.py +6 -5
- torch_geometric/loader/graph_saint.py +2 -1
- torch_geometric/loader/ibmb_loader.py +4 -4
- torch_geometric/loader/link_loader.py +1 -1
- torch_geometric/loader/link_neighbor_loader.py +2 -1
- torch_geometric/loader/mixin.py +6 -5
- torch_geometric/loader/neighbor_loader.py +1 -1
- torch_geometric/loader/neighbor_sampler.py +2 -2
- torch_geometric/loader/prefetch.py +4 -3
- torch_geometric/loader/temporal_dataloader.py +2 -2
- torch_geometric/loader/utils.py +10 -10
- torch_geometric/metrics/__init__.py +23 -2
- torch_geometric/metrics/link_pred.py +755 -85
- torch_geometric/nn/__init__.py +1 -0
- torch_geometric/nn/aggr/__init__.py +2 -0
- torch_geometric/nn/aggr/base.py +1 -1
- torch_geometric/nn/aggr/equilibrium.py +1 -1
- torch_geometric/nn/aggr/fused.py +1 -1
- torch_geometric/nn/aggr/patch_transformer.py +149 -0
- torch_geometric/nn/aggr/set_transformer.py +1 -1
- torch_geometric/nn/aggr/utils.py +9 -4
- torch_geometric/nn/attention/__init__.py +9 -1
- torch_geometric/nn/attention/polynormer.py +107 -0
- torch_geometric/nn/attention/qformer.py +71 -0
- torch_geometric/nn/attention/sgformer.py +99 -0
- torch_geometric/nn/conv/__init__.py +2 -0
- torch_geometric/nn/conv/appnp.py +1 -1
- torch_geometric/nn/conv/collect.jinja +6 -3
- torch_geometric/nn/conv/cugraph/gat_conv.py +8 -2
- torch_geometric/nn/conv/cugraph/rgcn_conv.py +3 -0
- torch_geometric/nn/conv/cugraph/sage_conv.py +3 -0
- torch_geometric/nn/conv/dna_conv.py +1 -1
- torch_geometric/nn/conv/eg_conv.py +7 -7
- torch_geometric/nn/conv/gat_conv.py +33 -4
- torch_geometric/nn/conv/gatv2_conv.py +35 -4
- torch_geometric/nn/conv/gen_conv.py +1 -1
- torch_geometric/nn/conv/general_conv.py +1 -1
- torch_geometric/nn/conv/gravnet_conv.py +2 -1
- torch_geometric/nn/conv/hetero_conv.py +3 -2
- torch_geometric/nn/conv/meshcnn_conv.py +487 -0
- torch_geometric/nn/conv/message_passing.py +6 -5
- torch_geometric/nn/conv/mixhop_conv.py +1 -1
- torch_geometric/nn/conv/rgcn_conv.py +2 -1
- torch_geometric/nn/conv/sg_conv.py +1 -1
- torch_geometric/nn/conv/spline_conv.py +2 -1
- torch_geometric/nn/conv/ssg_conv.py +1 -1
- torch_geometric/nn/conv/transformer_conv.py +5 -3
- torch_geometric/nn/data_parallel.py +5 -4
- torch_geometric/nn/dense/linear.py +5 -24
- torch_geometric/nn/encoding.py +17 -3
- torch_geometric/nn/fx.py +17 -15
- torch_geometric/nn/model_hub.py +5 -16
- torch_geometric/nn/models/__init__.py +11 -0
- torch_geometric/nn/models/attentive_fp.py +1 -1
- torch_geometric/nn/models/attract_repel.py +148 -0
- torch_geometric/nn/models/basic_gnn.py +2 -1
- torch_geometric/nn/models/captum.py +1 -1
- torch_geometric/nn/models/deep_graph_infomax.py +1 -1
- torch_geometric/nn/models/dimenet.py +2 -2
- torch_geometric/nn/models/dimenet_utils.py +4 -2
- torch_geometric/nn/models/gpse.py +1083 -0
- torch_geometric/nn/models/graph_unet.py +13 -4
- torch_geometric/nn/models/lpformer.py +783 -0
- torch_geometric/nn/models/metapath2vec.py +1 -1
- torch_geometric/nn/models/mlp.py +4 -2
- torch_geometric/nn/models/node2vec.py +1 -1
- torch_geometric/nn/models/polynormer.py +206 -0
- torch_geometric/nn/models/rev_gnn.py +3 -3
- torch_geometric/nn/models/schnet.py +2 -1
- torch_geometric/nn/models/sgformer.py +219 -0
- torch_geometric/nn/models/signed_gcn.py +1 -1
- torch_geometric/nn/models/visnet.py +2 -2
- torch_geometric/nn/norm/batch_norm.py +17 -7
- torch_geometric/nn/norm/diff_group_norm.py +7 -2
- torch_geometric/nn/norm/graph_norm.py +9 -4
- torch_geometric/nn/norm/instance_norm.py +5 -1
- torch_geometric/nn/norm/layer_norm.py +15 -7
- torch_geometric/nn/norm/msg_norm.py +8 -2
- torch_geometric/nn/pool/__init__.py +15 -9
- torch_geometric/nn/pool/cluster_pool.py +144 -0
- torch_geometric/nn/pool/connect/base.py +1 -3
- torch_geometric/nn/pool/edge_pool.py +1 -1
- torch_geometric/nn/pool/knn.py +13 -10
- torch_geometric/nn/pool/select/base.py +1 -4
- torch_geometric/nn/summary.py +1 -1
- torch_geometric/nn/to_hetero_module.py +4 -3
- torch_geometric/nn/to_hetero_transformer.py +3 -3
- torch_geometric/nn/to_hetero_with_bases_transformer.py +5 -5
- torch_geometric/profile/__init__.py +2 -0
- torch_geometric/profile/nvtx.py +66 -0
- torch_geometric/profile/profiler.py +18 -9
- torch_geometric/profile/utils.py +20 -5
- torch_geometric/sampler/__init__.py +2 -1
- torch_geometric/sampler/base.py +337 -8
- torch_geometric/sampler/hgt_sampler.py +11 -1
- torch_geometric/sampler/neighbor_sampler.py +298 -25
- torch_geometric/sampler/utils.py +93 -5
- torch_geometric/testing/__init__.py +4 -0
- torch_geometric/testing/decorators.py +35 -5
- torch_geometric/testing/distributed.py +1 -1
- torch_geometric/transforms/__init__.py +4 -0
- torch_geometric/transforms/add_gpse.py +49 -0
- torch_geometric/transforms/add_metapaths.py +10 -8
- torch_geometric/transforms/add_positional_encoding.py +2 -2
- torch_geometric/transforms/base_transform.py +2 -1
- torch_geometric/transforms/delaunay.py +65 -15
- torch_geometric/transforms/face_to_edge.py +32 -3
- torch_geometric/transforms/gdc.py +8 -9
- torch_geometric/transforms/largest_connected_components.py +1 -1
- torch_geometric/transforms/mask.py +5 -1
- torch_geometric/transforms/node_property_split.py +1 -1
- torch_geometric/transforms/normalize_features.py +3 -3
- torch_geometric/transforms/pad.py +1 -1
- torch_geometric/transforms/random_link_split.py +1 -1
- torch_geometric/transforms/remove_duplicated_edges.py +4 -2
- torch_geometric/transforms/remove_self_loops.py +36 -0
- torch_geometric/transforms/rooted_subgraph.py +1 -1
- torch_geometric/transforms/svd_feature_reduction.py +1 -1
- torch_geometric/transforms/virtual_node.py +2 -1
- torch_geometric/typing.py +82 -17
- torch_geometric/utils/__init__.py +6 -1
- torch_geometric/utils/_lexsort.py +0 -9
- torch_geometric/utils/_negative_sampling.py +28 -13
- torch_geometric/utils/_normalize_edge_index.py +46 -0
- torch_geometric/utils/_scatter.py +126 -164
- torch_geometric/utils/_sort_edge_index.py +0 -2
- torch_geometric/utils/_spmm.py +16 -14
- torch_geometric/utils/_subgraph.py +4 -0
- torch_geometric/utils/_tree_decomposition.py +1 -1
- torch_geometric/utils/_trim_to_layer.py +2 -2
- torch_geometric/utils/augmentation.py +1 -1
- torch_geometric/utils/convert.py +17 -10
- torch_geometric/utils/cross_entropy.py +34 -13
- torch_geometric/utils/embedding.py +91 -2
- torch_geometric/utils/geodesic.py +28 -25
- torch_geometric/utils/influence.py +279 -0
- torch_geometric/utils/map.py +14 -10
- torch_geometric/utils/nested.py +1 -1
- torch_geometric/utils/smiles.py +3 -3
- torch_geometric/utils/sparse.py +32 -24
- torch_geometric/visualization/__init__.py +2 -1
- torch_geometric/visualization/graph.py +250 -5
- torch_geometric/warnings.py +11 -2
- torch_geometric/nn/nlp/__init__.py +0 -7
- torch_geometric/nn/nlp/llm.py +0 -283
- torch_geometric/nn/nlp/sentence_transformer.py +0 -94
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
from typing import List, Optional
|
|
2
|
+
|
|
3
|
+
import torch
|
|
4
|
+
from torch import Tensor
|
|
5
|
+
|
|
6
|
+
from torch_geometric.llm.models.llm import BOS, LLM, MAX_NEW_TOKENS
|
|
7
|
+
from torch_geometric.nn.attention import QFormer
|
|
8
|
+
from torch_geometric.utils import to_dense_batch
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def pad_or_truncate(embeddings: Tensor, max_seq_len: int,
|
|
12
|
+
padding_value: int = 0) -> Tensor:
|
|
13
|
+
batch_size, current_seq_len, d = embeddings.size()
|
|
14
|
+
|
|
15
|
+
if current_seq_len > max_seq_len:
|
|
16
|
+
return embeddings[:, :max_seq_len, :]
|
|
17
|
+
elif current_seq_len < max_seq_len:
|
|
18
|
+
pad_tensor = torch.full((batch_size, max_seq_len - current_seq_len, d),
|
|
19
|
+
padding_value, dtype=embeddings.dtype,
|
|
20
|
+
device=embeddings.device)
|
|
21
|
+
return torch.cat([embeddings, pad_tensor], dim=1)
|
|
22
|
+
else:
|
|
23
|
+
return embeddings
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class MoleculeGPT(torch.nn.Module):
|
|
27
|
+
r"""The MoleculeGPT model from the `"MoleculeGPT: Instruction
|
|
28
|
+
Following Large Language Models for Molecular Property Prediction"
|
|
29
|
+
<https://ai4d3.github.io/papers/34.pdf>`_ paper.
|
|
30
|
+
|
|
31
|
+
Args:
|
|
32
|
+
llm (LLM): The LLM to use.
|
|
33
|
+
graph_encoder (torch.nn.Module): Encode 2D molecule graph.
|
|
34
|
+
smiles_encoder (torch.nn.Module): Encode 1D SMILES.
|
|
35
|
+
mlp_out_channels (int, optional): The size of each embedding
|
|
36
|
+
after qformer encoding. (default: :obj:`32`)
|
|
37
|
+
max_tokens (int, optional): Max output tokens of 1D/2D encoder.
|
|
38
|
+
(default: :obj:`20`)
|
|
39
|
+
|
|
40
|
+
.. warning::
|
|
41
|
+
This module has been tested with the following HuggingFace models
|
|
42
|
+
|
|
43
|
+
* :obj:`llm_to_use="lmsys/vicuna-7b-v1.5"`
|
|
44
|
+
|
|
45
|
+
and may not work with other models. See other models at `HuggingFace
|
|
46
|
+
Models <https://huggingface.co/models>`_ and let us know if you
|
|
47
|
+
encounter any issues.
|
|
48
|
+
|
|
49
|
+
.. note::
|
|
50
|
+
For an example of using :class:`MoleculeGPT`, see
|
|
51
|
+
`examples/llm/molecule_gpt.py <https://github.com/pyg-team/
|
|
52
|
+
pytorch_geometric/blob/master/examples/llm/molecule_gpt.py>`_.
|
|
53
|
+
"""
|
|
54
|
+
def __init__(
|
|
55
|
+
self,
|
|
56
|
+
llm: LLM,
|
|
57
|
+
graph_encoder: torch.nn.Module,
|
|
58
|
+
smiles_encoder: torch.nn.Module,
|
|
59
|
+
mlp_out_channels: int = 32,
|
|
60
|
+
max_tokens: Optional[int] = 20,
|
|
61
|
+
) -> None:
|
|
62
|
+
super().__init__()
|
|
63
|
+
self.llm = llm
|
|
64
|
+
self.graph_encoder = graph_encoder.to(self.llm.device)
|
|
65
|
+
self.smiles_encoder = smiles_encoder.to(self.llm.device)
|
|
66
|
+
|
|
67
|
+
self.graph_qformer = QFormer(
|
|
68
|
+
input_dim=self.graph_encoder.nn[-1].out_features,
|
|
69
|
+
hidden_dim=mlp_out_channels,
|
|
70
|
+
output_dim=mlp_out_channels,
|
|
71
|
+
num_heads=4,
|
|
72
|
+
num_layers=2,
|
|
73
|
+
).to(self.llm.device)
|
|
74
|
+
|
|
75
|
+
self.smiles_qformer = QFormer(
|
|
76
|
+
input_dim=self.smiles_encoder.model.pooler.dense.out_features,
|
|
77
|
+
hidden_dim=mlp_out_channels,
|
|
78
|
+
output_dim=mlp_out_channels,
|
|
79
|
+
num_heads=4,
|
|
80
|
+
num_layers=2,
|
|
81
|
+
).to(self.llm.device)
|
|
82
|
+
|
|
83
|
+
self.max_tokens = max_tokens
|
|
84
|
+
|
|
85
|
+
self.word_embedding = self.llm.word_embedding
|
|
86
|
+
self.llm_generator = self.llm.llm
|
|
87
|
+
|
|
88
|
+
# LLMs
|
|
89
|
+
in_dim = 2 * mlp_out_channels * max_tokens
|
|
90
|
+
out_dim = self.llm.llm.model.embed_tokens.embedding_dim
|
|
91
|
+
self.projector = torch.nn.Sequential(
|
|
92
|
+
torch.nn.Linear(in_dim, in_dim),
|
|
93
|
+
torch.nn.Sigmoid(),
|
|
94
|
+
torch.nn.Linear(in_dim, out_dim),
|
|
95
|
+
).to(self.llm.device)
|
|
96
|
+
|
|
97
|
+
def encode(
|
|
98
|
+
self,
|
|
99
|
+
x: Tensor,
|
|
100
|
+
edge_index: Tensor,
|
|
101
|
+
batch: Tensor,
|
|
102
|
+
edge_attr: Optional[Tensor],
|
|
103
|
+
smiles: List[str],
|
|
104
|
+
) -> Tensor:
|
|
105
|
+
batch_size = len(smiles)
|
|
106
|
+
# 2D Graph Branch: [bs, node_len, d]
|
|
107
|
+
x = x.to(self.llm.device)
|
|
108
|
+
edge_index = edge_index.to(self.llm.device)
|
|
109
|
+
if edge_attr is not None:
|
|
110
|
+
edge_attr = edge_attr.to(self.llm.device)
|
|
111
|
+
batch = batch.to(self.llm.device)
|
|
112
|
+
|
|
113
|
+
x_graph = self.graph_encoder(x, edge_index, edge_attr=edge_attr)
|
|
114
|
+
x_graph = to_dense_batch(x_graph, batch)[0]
|
|
115
|
+
out_graph = self.graph_qformer(x_graph)
|
|
116
|
+
out_graph = pad_or_truncate(out_graph, max_seq_len=self.max_tokens,
|
|
117
|
+
padding_value=0)
|
|
118
|
+
out_graph = out_graph.view(batch_size, -1)
|
|
119
|
+
|
|
120
|
+
# 1D SMILES Branch: [bs, seq_len, d]
|
|
121
|
+
x_smiles = self.smiles_encoder.encode(smiles,
|
|
122
|
+
output_device=self.llm.device)
|
|
123
|
+
out_smiles = self.smiles_qformer(x_smiles)
|
|
124
|
+
out_smiles = pad_or_truncate(out_smiles, max_seq_len=self.max_tokens,
|
|
125
|
+
padding_value=0)
|
|
126
|
+
out_smiles = out_smiles.view(batch_size, -1)
|
|
127
|
+
|
|
128
|
+
# Merge into LLMs
|
|
129
|
+
x_cat = torch.cat([out_graph, out_smiles], dim=1)
|
|
130
|
+
return x_cat
|
|
131
|
+
|
|
132
|
+
def forward(
|
|
133
|
+
self,
|
|
134
|
+
x: Tensor,
|
|
135
|
+
edge_index: Tensor,
|
|
136
|
+
batch: Tensor,
|
|
137
|
+
edge_attr: Optional[Tensor],
|
|
138
|
+
smiles: List[str],
|
|
139
|
+
instructions: List[str],
|
|
140
|
+
label: List[str],
|
|
141
|
+
additional_text_context: Optional[List[str]] = None,
|
|
142
|
+
):
|
|
143
|
+
x = self.encode(x, edge_index, batch, edge_attr, smiles)
|
|
144
|
+
x = self.projector(x)
|
|
145
|
+
xs = x.split(1, dim=0)
|
|
146
|
+
|
|
147
|
+
batch_unique = batch.unique()
|
|
148
|
+
batch_size = len(instructions)
|
|
149
|
+
if len(batch_unique) < batch_size:
|
|
150
|
+
xs = [
|
|
151
|
+
xs[i] if i in batch_unique else None for i in range(batch_size)
|
|
152
|
+
]
|
|
153
|
+
|
|
154
|
+
(
|
|
155
|
+
inputs_embeds,
|
|
156
|
+
attention_mask,
|
|
157
|
+
label_input_ids,
|
|
158
|
+
) = self.llm._get_embeds(instructions, additional_text_context, xs,
|
|
159
|
+
label)
|
|
160
|
+
|
|
161
|
+
with self.llm.autocast_context:
|
|
162
|
+
outputs = self.llm_generator(
|
|
163
|
+
inputs_embeds=inputs_embeds,
|
|
164
|
+
attention_mask=attention_mask,
|
|
165
|
+
return_dict=True,
|
|
166
|
+
labels=label_input_ids,
|
|
167
|
+
)
|
|
168
|
+
|
|
169
|
+
return outputs.loss
|
|
170
|
+
|
|
171
|
+
@torch.no_grad()
|
|
172
|
+
def inference(
|
|
173
|
+
self,
|
|
174
|
+
x: Tensor,
|
|
175
|
+
edge_index: Tensor,
|
|
176
|
+
batch: Tensor,
|
|
177
|
+
edge_attr: Optional[Tensor],
|
|
178
|
+
smiles: List[str],
|
|
179
|
+
instructions: List[str],
|
|
180
|
+
additional_text_context: Optional[List[str]] = None,
|
|
181
|
+
max_out_tokens: Optional[int] = MAX_NEW_TOKENS,
|
|
182
|
+
):
|
|
183
|
+
x = self.encode(x, edge_index, batch, edge_attr, smiles)
|
|
184
|
+
x = self.projector(x)
|
|
185
|
+
xs = x.split(1, dim=0)
|
|
186
|
+
|
|
187
|
+
# Handle questions without node features:
|
|
188
|
+
batch_unique = batch.unique()
|
|
189
|
+
batch_size = len(instructions)
|
|
190
|
+
if len(batch_unique) < batch_size:
|
|
191
|
+
xs = [
|
|
192
|
+
xs[i] if i in batch_unique else None for i in range(batch_size)
|
|
193
|
+
]
|
|
194
|
+
|
|
195
|
+
inputs_embeds, attention_mask, _ = self.llm._get_embeds(
|
|
196
|
+
instructions, additional_text_context, xs)
|
|
197
|
+
|
|
198
|
+
bos_token = self.llm.tokenizer(
|
|
199
|
+
BOS,
|
|
200
|
+
add_special_tokens=False,
|
|
201
|
+
).input_ids[0]
|
|
202
|
+
|
|
203
|
+
with self.llm.autocast_context:
|
|
204
|
+
outputs = self.llm_generator.generate(
|
|
205
|
+
inputs_embeds=inputs_embeds,
|
|
206
|
+
max_new_tokens=max_out_tokens,
|
|
207
|
+
attention_mask=attention_mask,
|
|
208
|
+
bos_token_id=bos_token,
|
|
209
|
+
use_cache=True # Important to set!
|
|
210
|
+
)
|
|
211
|
+
|
|
212
|
+
return self.llm.tokenizer.batch_decode(
|
|
213
|
+
outputs,
|
|
214
|
+
skip_special_tokens=True,
|
|
215
|
+
)
|
|
216
|
+
|
|
217
|
+
def __repr__(self) -> str:
|
|
218
|
+
return (f'{self.__class__.__name__}(\n'
|
|
219
|
+
f' llm={self.llm},\n'
|
|
220
|
+
f' graph={self.graph_encoder.__class__.__name__},\n'
|
|
221
|
+
f' smiles={self.smiles_encoder},\n'
|
|
222
|
+
f')')
|
|
@@ -0,0 +1,333 @@
|
|
|
1
|
+
from itertools import product
|
|
2
|
+
from typing import Tuple
|
|
3
|
+
|
|
4
|
+
import torch
|
|
5
|
+
import torch.nn.functional as F
|
|
6
|
+
|
|
7
|
+
from torch_geometric.nn import knn_graph
|
|
8
|
+
from torch_geometric.nn.conv import MessagePassing
|
|
9
|
+
from torch_geometric.utils import to_dense_adj, to_dense_batch
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class PositionWiseFeedForward(torch.nn.Module):
|
|
13
|
+
def __init__(self, in_channels: int, hidden_channels: int) -> None:
|
|
14
|
+
super().__init__()
|
|
15
|
+
self.out = torch.nn.Sequential(
|
|
16
|
+
torch.nn.Linear(in_channels, hidden_channels),
|
|
17
|
+
torch.nn.GELU(),
|
|
18
|
+
torch.nn.Linear(hidden_channels, in_channels),
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
|
22
|
+
return self.out(x)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class PositionalEncoding(torch.nn.Module):
|
|
26
|
+
def __init__(self, hidden_channels: int,
|
|
27
|
+
max_relative_feature: int = 32) -> None:
|
|
28
|
+
super().__init__()
|
|
29
|
+
self.max_relative_feature = max_relative_feature
|
|
30
|
+
self.emb = torch.nn.Embedding(2 * max_relative_feature + 2,
|
|
31
|
+
hidden_channels)
|
|
32
|
+
|
|
33
|
+
def forward(self, offset, mask) -> torch.Tensor:
|
|
34
|
+
d = torch.clip(offset + self.max_relative_feature, 0,
|
|
35
|
+
2 * self.max_relative_feature) * mask + (1 - mask) * (
|
|
36
|
+
2 * self.max_relative_feature + 1) # noqa: E501
|
|
37
|
+
return self.emb(d.long())
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class Encoder(MessagePassing):
|
|
41
|
+
def __init__(
|
|
42
|
+
self,
|
|
43
|
+
in_channels: int,
|
|
44
|
+
hidden_channels: int,
|
|
45
|
+
dropout: float = 0.1,
|
|
46
|
+
scale: float = 30,
|
|
47
|
+
) -> None:
|
|
48
|
+
super().__init__()
|
|
49
|
+
self.out_v = torch.nn.Sequential(
|
|
50
|
+
torch.nn.Linear(in_channels, hidden_channels),
|
|
51
|
+
torch.nn.GELU(),
|
|
52
|
+
torch.nn.Linear(hidden_channels, hidden_channels),
|
|
53
|
+
torch.nn.GELU(),
|
|
54
|
+
torch.nn.Linear(hidden_channels, hidden_channels),
|
|
55
|
+
)
|
|
56
|
+
self.out_e = torch.nn.Sequential(
|
|
57
|
+
torch.nn.Linear(in_channels, hidden_channels),
|
|
58
|
+
torch.nn.GELU(),
|
|
59
|
+
torch.nn.Linear(hidden_channels, hidden_channels),
|
|
60
|
+
torch.nn.GELU(),
|
|
61
|
+
torch.nn.Linear(hidden_channels, hidden_channels),
|
|
62
|
+
)
|
|
63
|
+
self.dropout1 = torch.nn.Dropout(dropout)
|
|
64
|
+
self.dropout2 = torch.nn.Dropout(dropout)
|
|
65
|
+
self.dropout3 = torch.nn.Dropout(dropout)
|
|
66
|
+
self.norm1 = torch.nn.LayerNorm(hidden_channels)
|
|
67
|
+
self.norm2 = torch.nn.LayerNorm(hidden_channels)
|
|
68
|
+
self.norm3 = torch.nn.LayerNorm(hidden_channels)
|
|
69
|
+
self.scale = scale
|
|
70
|
+
self.dense = PositionWiseFeedForward(hidden_channels,
|
|
71
|
+
hidden_channels * 4)
|
|
72
|
+
|
|
73
|
+
def forward(
|
|
74
|
+
self,
|
|
75
|
+
x: torch.Tensor,
|
|
76
|
+
edge_index: torch.Tensor,
|
|
77
|
+
edge_attr: torch.Tensor,
|
|
78
|
+
) -> torch.Tensor:
|
|
79
|
+
# x: [N, d_v]
|
|
80
|
+
# edge_index: [2, E]
|
|
81
|
+
# edge_attr: [E, d_e]
|
|
82
|
+
# update node features
|
|
83
|
+
h_message = self.propagate(x=x, edge_index=edge_index,
|
|
84
|
+
edge_attr=edge_attr)
|
|
85
|
+
dh = h_message / self.scale
|
|
86
|
+
x = self.norm1(x + self.dropout1(dh))
|
|
87
|
+
dh = self.dense(x)
|
|
88
|
+
x = self.norm2(x + self.dropout2(dh))
|
|
89
|
+
# update edge features
|
|
90
|
+
row, col = edge_index
|
|
91
|
+
x_i, x_j = x[row], x[col]
|
|
92
|
+
h_e = torch.cat([x_i, x_j, edge_attr], dim=-1)
|
|
93
|
+
h_e = self.out_e(h_e)
|
|
94
|
+
edge_attr = self.norm3(edge_attr + self.dropout3(h_e))
|
|
95
|
+
return x, edge_attr
|
|
96
|
+
|
|
97
|
+
def message(self, x_i: torch.Tensor, x_j: torch.Tensor,
|
|
98
|
+
edge_attr: torch.Tensor) -> torch.Tensor:
|
|
99
|
+
h = torch.cat([x_i, x_j, edge_attr], dim=-1) # [E, 2*d_v + d_e]
|
|
100
|
+
h = self.out_e(h) # [E, d_e]
|
|
101
|
+
return h
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
class Decoder(MessagePassing):
|
|
105
|
+
def __init__(
|
|
106
|
+
self,
|
|
107
|
+
in_channels: int,
|
|
108
|
+
hidden_channels: int,
|
|
109
|
+
dropout: float = 0.1,
|
|
110
|
+
scale: float = 30,
|
|
111
|
+
) -> None:
|
|
112
|
+
super().__init__()
|
|
113
|
+
self.out_v = torch.nn.Sequential(
|
|
114
|
+
torch.nn.Linear(in_channels, hidden_channels),
|
|
115
|
+
torch.nn.GELU(),
|
|
116
|
+
torch.nn.Linear(hidden_channels, hidden_channels),
|
|
117
|
+
torch.nn.GELU(),
|
|
118
|
+
torch.nn.Linear(hidden_channels, hidden_channels),
|
|
119
|
+
)
|
|
120
|
+
self.dropout1 = torch.nn.Dropout(dropout)
|
|
121
|
+
self.dropout2 = torch.nn.Dropout(dropout)
|
|
122
|
+
self.norm1 = torch.nn.LayerNorm(hidden_channels)
|
|
123
|
+
self.norm2 = torch.nn.LayerNorm(hidden_channels)
|
|
124
|
+
self.scale = scale
|
|
125
|
+
self.dense = PositionWiseFeedForward(hidden_channels,
|
|
126
|
+
hidden_channels * 4)
|
|
127
|
+
|
|
128
|
+
def forward(
|
|
129
|
+
self,
|
|
130
|
+
x: torch.Tensor,
|
|
131
|
+
edge_index: torch.Tensor,
|
|
132
|
+
edge_attr: torch.Tensor,
|
|
133
|
+
x_label: torch.Tensor,
|
|
134
|
+
mask: torch.Tensor,
|
|
135
|
+
) -> torch.Tensor:
|
|
136
|
+
# x: [N, d_v]
|
|
137
|
+
# edge_index: [2, E]
|
|
138
|
+
# edge_attr: [E, d_e]
|
|
139
|
+
h_message = self.propagate(x=x, x_label=x_label, edge_index=edge_index,
|
|
140
|
+
edge_attr=edge_attr, mask=mask)
|
|
141
|
+
dh = h_message / self.scale
|
|
142
|
+
x = self.norm1(x + self.dropout1(dh))
|
|
143
|
+
dh = self.dense(x)
|
|
144
|
+
x = self.norm2(x + self.dropout2(dh))
|
|
145
|
+
return x
|
|
146
|
+
|
|
147
|
+
def message(self, x_i: torch.Tensor, x_j: torch.Tensor,
|
|
148
|
+
x_label_j: torch.Tensor, edge_attr: torch.Tensor,
|
|
149
|
+
mask: torch.Tensor) -> torch.Tensor:
|
|
150
|
+
h_1 = torch.cat([x_j, edge_attr, x_label_j], dim=-1)
|
|
151
|
+
h_0 = torch.cat([x_j, edge_attr, torch.zeros_like(x_label_j)], dim=-1)
|
|
152
|
+
h = h_1 * mask + h_0 * (1 - mask)
|
|
153
|
+
h = torch.concat([x_i, h], dim=-1)
|
|
154
|
+
h = self.out_v(h)
|
|
155
|
+
return h
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
class ProteinMPNN(torch.nn.Module):
|
|
159
|
+
r"""The ProteinMPNN model from the `"Robust deep learning--based
|
|
160
|
+
protein sequence design using ProteinMPNN"
|
|
161
|
+
<https://www.biorxiv.org/content/10.1101/2022.06.03.494563v1>`_ paper.
|
|
162
|
+
|
|
163
|
+
Args:
|
|
164
|
+
hidden_dim (int): Hidden channels.
|
|
165
|
+
(default: :obj:`128`)
|
|
166
|
+
num_encoder_layers (int): Number of encode layers.
|
|
167
|
+
(default: :obj:`3`)
|
|
168
|
+
num_decoder_layers (int): Number of decode layers.
|
|
169
|
+
(default: :obj:`3`)
|
|
170
|
+
num_neighbors (int): Number of neighbors for each atom.
|
|
171
|
+
(default: :obj:`30`)
|
|
172
|
+
num_rbf (int): Number of radial basis functions.
|
|
173
|
+
(default: :obj:`16`)
|
|
174
|
+
dropout (float): Dropout rate.
|
|
175
|
+
(default: :obj:`0.1`)
|
|
176
|
+
augment_eps (float): Augmentation epsilon for input coordinates.
|
|
177
|
+
(default: :obj:`0.2`)
|
|
178
|
+
num_positional_embedding (int): Number of positional embeddings.
|
|
179
|
+
(default: :obj:`16`)
|
|
180
|
+
vocab_size (int): Number of vocabulary.
|
|
181
|
+
(default: :obj:`21`)
|
|
182
|
+
|
|
183
|
+
.. note::
|
|
184
|
+
For an example of using :class:`ProteinMPNN`, see
|
|
185
|
+
`examples/llm/protein_mpnn.py <https://github.com/pyg-team/
|
|
186
|
+
pytorch_geometric/blob/master/examples/llm/protein_mpnn.py>`_.
|
|
187
|
+
"""
|
|
188
|
+
def __init__(
|
|
189
|
+
self,
|
|
190
|
+
hidden_dim: int = 128,
|
|
191
|
+
num_encoder_layers: int = 3,
|
|
192
|
+
num_decoder_layers: int = 3,
|
|
193
|
+
num_neighbors: int = 30,
|
|
194
|
+
num_rbf: int = 16,
|
|
195
|
+
dropout: float = 0.1,
|
|
196
|
+
augment_eps: float = 0.2,
|
|
197
|
+
num_positional_embedding: int = 16,
|
|
198
|
+
vocab_size: int = 21,
|
|
199
|
+
) -> None:
|
|
200
|
+
super().__init__()
|
|
201
|
+
self.augment_eps = augment_eps
|
|
202
|
+
self.hidden_dim = hidden_dim
|
|
203
|
+
self.num_neighbors = num_neighbors
|
|
204
|
+
self.num_rbf = num_rbf
|
|
205
|
+
self.embedding = PositionalEncoding(num_positional_embedding)
|
|
206
|
+
self.edge_mlp = torch.nn.Sequential(
|
|
207
|
+
torch.nn.Linear(num_positional_embedding + 400, hidden_dim),
|
|
208
|
+
torch.nn.LayerNorm(hidden_dim),
|
|
209
|
+
torch.nn.Linear(hidden_dim, hidden_dim),
|
|
210
|
+
)
|
|
211
|
+
self.label_embedding = torch.nn.Embedding(vocab_size, hidden_dim)
|
|
212
|
+
self.encoder_layers = torch.nn.ModuleList([
|
|
213
|
+
Encoder(hidden_dim * 3, hidden_dim, dropout)
|
|
214
|
+
for _ in range(num_encoder_layers)
|
|
215
|
+
])
|
|
216
|
+
|
|
217
|
+
self.decoder_layers = torch.nn.ModuleList([
|
|
218
|
+
Decoder(hidden_dim * 4, hidden_dim, dropout)
|
|
219
|
+
for _ in range(num_decoder_layers)
|
|
220
|
+
])
|
|
221
|
+
self.output = torch.nn.Linear(hidden_dim, vocab_size)
|
|
222
|
+
|
|
223
|
+
self.reset_parameters()
|
|
224
|
+
|
|
225
|
+
def reset_parameters(self):
|
|
226
|
+
for p in self.parameters():
|
|
227
|
+
if p.dim() > 1:
|
|
228
|
+
torch.nn.init.xavier_uniform_(p)
|
|
229
|
+
|
|
230
|
+
def _featurize(
|
|
231
|
+
self,
|
|
232
|
+
x: torch.Tensor,
|
|
233
|
+
mask: torch.Tensor,
|
|
234
|
+
batch: torch.Tensor,
|
|
235
|
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
|
236
|
+
N, Ca, C, O = (x[:, i, :] for i in range(4)) # noqa: E741
|
|
237
|
+
b = Ca - N
|
|
238
|
+
c = C - Ca
|
|
239
|
+
a = torch.cross(b, c, dim=-1)
|
|
240
|
+
Cb = -0.58273431 * a + 0.56802827 * b - 0.54067466 * c + Ca
|
|
241
|
+
|
|
242
|
+
valid_mask = mask.bool()
|
|
243
|
+
valid_Ca = Ca[valid_mask]
|
|
244
|
+
valid_batch = batch[valid_mask]
|
|
245
|
+
|
|
246
|
+
edge_index = knn_graph(valid_Ca, k=self.num_neighbors,
|
|
247
|
+
batch=valid_batch, loop=True)
|
|
248
|
+
|
|
249
|
+
row, col = edge_index
|
|
250
|
+
original_indices = torch.arange(Ca.size(0),
|
|
251
|
+
device=x.device)[valid_mask]
|
|
252
|
+
edge_index_original = torch.stack(
|
|
253
|
+
[original_indices[row], original_indices[col]], dim=0)
|
|
254
|
+
row, col = edge_index_original
|
|
255
|
+
|
|
256
|
+
rbf_all = []
|
|
257
|
+
for A, B in list(product([N, Ca, C, O, Cb], repeat=2)):
|
|
258
|
+
distances = torch.sqrt(torch.sum((A[row] - B[col])**2, 1) + 1e-6)
|
|
259
|
+
rbf = self._rbf(distances)
|
|
260
|
+
rbf_all.append(rbf)
|
|
261
|
+
|
|
262
|
+
return edge_index_original, torch.cat(rbf_all, dim=-1)
|
|
263
|
+
|
|
264
|
+
def _rbf(self, D: torch.Tensor) -> torch.Tensor:
|
|
265
|
+
D_min, D_max, D_count = 2., 22., self.num_rbf
|
|
266
|
+
D_mu = torch.linspace(D_min, D_max, D_count, device=D.device)
|
|
267
|
+
D_mu = D_mu.view([1, -1])
|
|
268
|
+
D_sigma = (D_max - D_min) / D_count
|
|
269
|
+
D_expand = torch.unsqueeze(D, -1)
|
|
270
|
+
RBF = torch.exp(-((D_expand - D_mu) / D_sigma)**2)
|
|
271
|
+
return RBF
|
|
272
|
+
|
|
273
|
+
def forward(
|
|
274
|
+
self,
|
|
275
|
+
x: torch.Tensor,
|
|
276
|
+
chain_seq_label: torch.Tensor,
|
|
277
|
+
mask: torch.Tensor,
|
|
278
|
+
chain_mask_all: torch.Tensor,
|
|
279
|
+
residue_idx: torch.Tensor,
|
|
280
|
+
chain_encoding_all: torch.Tensor,
|
|
281
|
+
batch: torch.Tensor,
|
|
282
|
+
) -> torch.Tensor:
|
|
283
|
+
device = x.device
|
|
284
|
+
if self.training and self.augment_eps > 0:
|
|
285
|
+
x = x + self.augment_eps * torch.randn_like(x)
|
|
286
|
+
|
|
287
|
+
edge_index, edge_attr = self._featurize(x, mask, batch)
|
|
288
|
+
|
|
289
|
+
row, col = edge_index
|
|
290
|
+
offset = residue_idx[row] - residue_idx[col]
|
|
291
|
+
# find self vs non-self interaction
|
|
292
|
+
e_chains = ((chain_encoding_all[row] -
|
|
293
|
+
chain_encoding_all[col]) == 0).long()
|
|
294
|
+
e_pos = self.embedding(offset, e_chains)
|
|
295
|
+
h_e = self.edge_mlp(torch.cat([edge_attr, e_pos], dim=-1))
|
|
296
|
+
h_v = torch.zeros(x.size(0), self.hidden_dim, device=x.device)
|
|
297
|
+
|
|
298
|
+
# encoder
|
|
299
|
+
for encoder in self.encoder_layers:
|
|
300
|
+
h_v, h_e = encoder(h_v, edge_index, h_e)
|
|
301
|
+
|
|
302
|
+
# mask
|
|
303
|
+
h_label = self.label_embedding(chain_seq_label)
|
|
304
|
+
batch_chain_mask_all, _ = to_dense_batch(chain_mask_all * mask,
|
|
305
|
+
batch) # [B, N]
|
|
306
|
+
# 0 - visible - encoder, 1 - masked - decoder
|
|
307
|
+
decoding_order = torch.argsort(
|
|
308
|
+
(batch_chain_mask_all + 1e-4) * (torch.abs(
|
|
309
|
+
torch.randn(batch_chain_mask_all.shape, device=device))))
|
|
310
|
+
mask_size = batch_chain_mask_all.size(1)
|
|
311
|
+
permutation_matrix_reverse = F.one_hot(decoding_order,
|
|
312
|
+
num_classes=mask_size).float()
|
|
313
|
+
order_mask_backward = torch.einsum(
|
|
314
|
+
'ij, biq, bjp->bqp',
|
|
315
|
+
1 - torch.triu(torch.ones(mask_size, mask_size, device=device)),
|
|
316
|
+
permutation_matrix_reverse,
|
|
317
|
+
permutation_matrix_reverse,
|
|
318
|
+
)
|
|
319
|
+
adj = to_dense_adj(edge_index, batch)
|
|
320
|
+
mask_attend = order_mask_backward[adj.bool()].unsqueeze(-1)
|
|
321
|
+
|
|
322
|
+
# decoder
|
|
323
|
+
for decoder in self.decoder_layers:
|
|
324
|
+
h_v = decoder(
|
|
325
|
+
h_v,
|
|
326
|
+
edge_index,
|
|
327
|
+
h_e,
|
|
328
|
+
h_label,
|
|
329
|
+
mask_attend,
|
|
330
|
+
)
|
|
331
|
+
|
|
332
|
+
logits = self.output(h_v)
|
|
333
|
+
return F.log_softmax(logits, dim=-1)
|