pyg-nightly 2.7.0.dev20241009__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.7.0.dev20241009.dist-info → pyg_nightly-2.8.0.dev20251207.dist-info}/METADATA +77 -53
- {pyg_nightly-2.7.0.dev20241009.dist-info → pyg_nightly-2.8.0.dev20251207.dist-info}/RECORD +226 -189
- {pyg_nightly-2.7.0.dev20241009.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 +14 -2
- torch_geometric/_compile.py +9 -3
- torch_geometric/_onnx.py +214 -0
- torch_geometric/config_mixin.py +5 -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/batch.py +2 -2
- torch_geometric/data/collate.py +1 -3
- torch_geometric/data/data.py +109 -5
- torch_geometric/data/database.py +4 -0
- torch_geometric/data/dataset.py +14 -11
- 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 +18 -1
- torch_geometric/datasets/actor.py +7 -9
- torch_geometric/datasets/airfrans.py +15 -17
- 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/city.py +157 -0
- torch_geometric/datasets/dbp15k.py +1 -1
- torch_geometric/datasets/git_mol_dataset.py +263 -0
- 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/md17.py +3 -3
- torch_geometric/datasets/medshapenet.py +145 -0
- 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/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 +1 -1
- 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 +310 -209
- torch_geometric/datasets/wikics.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/partition.py +2 -2
- torch_geometric/distributed/rpc.py +3 -3
- torch_geometric/edge_index.py +18 -14
- 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 +87 -3
- torch_geometric/explain/metric/faithfulness.py +1 -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 +14 -5
- torch_geometric/inspector.py +4 -0
- torch_geometric/io/fs.py +5 -4
- 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/{nn → llm}/models/g_retriever.py +77 -45
- torch_geometric/llm/models/git_mol.py +336 -0
- torch_geometric/llm/models/glem.py +397 -0
- torch_geometric/{nn/nlp → llm/models}/llm.py +179 -31
- 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 +4 -4
- 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 +3 -2
- torch_geometric/loader/temporal_dataloader.py +2 -2
- torch_geometric/loader/utils.py +10 -10
- torch_geometric/metrics/__init__.py +14 -0
- torch_geometric/metrics/link_pred.py +745 -92
- torch_geometric/nn/__init__.py +1 -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 +8 -2
- 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/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/gen_conv.py +1 -1
- torch_geometric/nn/conv/gravnet_conv.py +2 -1
- torch_geometric/nn/conv/hetero_conv.py +2 -1
- torch_geometric/nn/conv/meshcnn_conv.py +487 -0
- torch_geometric/nn/conv/message_passing.py +5 -4
- 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 +0 -20
- torch_geometric/nn/encoding.py +17 -3
- torch_geometric/nn/fx.py +14 -12
- torch_geometric/nn/model_hub.py +2 -15
- torch_geometric/nn/models/__init__.py +11 -2
- 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/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 +8 -4
- torch_geometric/nn/pool/cluster_pool.py +3 -4
- torch_geometric/nn/pool/connect/base.py +1 -3
- torch_geometric/nn/pool/knn.py +13 -10
- torch_geometric/nn/pool/select/base.py +1 -4
- 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 +4 -4
- torch_geometric/profile/__init__.py +2 -0
- torch_geometric/profile/nvtx.py +66 -0
- torch_geometric/profile/utils.py +20 -5
- torch_geometric/sampler/__init__.py +2 -1
- torch_geometric/sampler/base.py +336 -7
- torch_geometric/sampler/hgt_sampler.py +11 -1
- torch_geometric/sampler/neighbor_sampler.py +296 -23
- 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 +2 -0
- torch_geometric/transforms/add_gpse.py +49 -0
- torch_geometric/transforms/add_metapaths.py +8 -6
- 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 +7 -8
- torch_geometric/transforms/largest_connected_components.py +1 -1
- torch_geometric/transforms/mask.py +5 -1
- torch_geometric/transforms/normalize_features.py +3 -3
- torch_geometric/transforms/random_link_split.py +1 -1
- torch_geometric/transforms/remove_duplicated_edges.py +4 -2
- torch_geometric/transforms/rooted_subgraph.py +1 -1
- torch_geometric/typing.py +70 -17
- torch_geometric/utils/__init__.py +4 -1
- torch_geometric/utils/_lexsort.py +0 -9
- torch_geometric/utils/_negative_sampling.py +27 -12
- torch_geometric/utils/_scatter.py +132 -195
- 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/_trim_to_layer.py +2 -2
- 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 +4 -3
- torch_geometric/utils/influence.py +279 -0
- torch_geometric/utils/map.py +13 -9
- torch_geometric/utils/nested.py +1 -1
- torch_geometric/utils/smiles.py +3 -3
- torch_geometric/utils/sparse.py +7 -14
- 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/sentence_transformer.py +0 -101
|
@@ -0,0 +1,741 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import pickle as pkl
|
|
3
|
+
import shutil
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from itertools import chain, islice, tee
|
|
6
|
+
from typing import (
|
|
7
|
+
Any,
|
|
8
|
+
Callable,
|
|
9
|
+
Dict,
|
|
10
|
+
Iterable,
|
|
11
|
+
Iterator,
|
|
12
|
+
List,
|
|
13
|
+
Optional,
|
|
14
|
+
Sequence,
|
|
15
|
+
Set,
|
|
16
|
+
Tuple,
|
|
17
|
+
Union,
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
import torch
|
|
21
|
+
from torch import Tensor
|
|
22
|
+
from tqdm import tqdm
|
|
23
|
+
|
|
24
|
+
from torch_geometric.data import Data
|
|
25
|
+
from torch_geometric.io import fs
|
|
26
|
+
from torch_geometric.typing import WITH_PT24
|
|
27
|
+
|
|
28
|
+
# Could be any hashable type
|
|
29
|
+
TripletLike = Tuple[str, str, str]
|
|
30
|
+
|
|
31
|
+
KnowledgeGraphLike = Iterable[TripletLike]
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def ordered_set(values: Iterable[str]) -> List[str]:
|
|
35
|
+
return list(dict.fromkeys(values))
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
# TODO: Refactor Node and Edge funcs and attrs to be accessible via an Enum?
|
|
39
|
+
|
|
40
|
+
NODE_PID = "pid" # Encodes node id
|
|
41
|
+
|
|
42
|
+
NODE_KEYS = {NODE_PID}
|
|
43
|
+
|
|
44
|
+
EDGE_PID = "e_pid" # Encodes source node, relation, destination node
|
|
45
|
+
EDGE_HEAD = "h" # Encodes source node
|
|
46
|
+
EDGE_RELATION = "r" # Encodes relation
|
|
47
|
+
EDGE_TAIL = "t" # Encodes destination node
|
|
48
|
+
EDGE_INDEX = "edge_idx" # Encodes source node, destination node
|
|
49
|
+
|
|
50
|
+
EDGE_KEYS = {EDGE_PID, EDGE_HEAD, EDGE_RELATION, EDGE_TAIL, EDGE_INDEX}
|
|
51
|
+
|
|
52
|
+
FeatureValueType = Union[Sequence[Any], Tensor]
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@dataclass
|
|
56
|
+
class MappedFeature:
|
|
57
|
+
name: str
|
|
58
|
+
values: FeatureValueType
|
|
59
|
+
|
|
60
|
+
def __eq__(self, value: "MappedFeature") -> bool:
|
|
61
|
+
eq = self.name == value.name
|
|
62
|
+
if isinstance(self.values, torch.Tensor):
|
|
63
|
+
eq &= torch.equal(self.values, value.values)
|
|
64
|
+
else:
|
|
65
|
+
eq &= self.values == value.values
|
|
66
|
+
return eq
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
if WITH_PT24:
|
|
70
|
+
torch.serialization.add_safe_globals([MappedFeature])
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class LargeGraphIndexer:
|
|
74
|
+
"""For a dataset that consists of multiple subgraphs that are assumed to
|
|
75
|
+
be part of a much larger graph, collate the values into a large graph store
|
|
76
|
+
to save resources.
|
|
77
|
+
"""
|
|
78
|
+
def __init__(
|
|
79
|
+
self,
|
|
80
|
+
nodes: Iterable[str],
|
|
81
|
+
edges: KnowledgeGraphLike,
|
|
82
|
+
node_attr: Optional[Dict[str, List[Any]]] = None,
|
|
83
|
+
edge_attr: Optional[Dict[str, List[Any]]] = None,
|
|
84
|
+
) -> None:
|
|
85
|
+
r"""Constructs a new index that uniquely catalogs each node and edge
|
|
86
|
+
by id. Not meant to be used directly.
|
|
87
|
+
|
|
88
|
+
Args:
|
|
89
|
+
nodes (Iterable[str]): Node ids in the graph.
|
|
90
|
+
edges (KnowledgeGraphLike): Edge ids in the graph.
|
|
91
|
+
Example: [("cats", "eat", "dogs")]
|
|
92
|
+
node_attr (Optional[Dict[str, List[Any]]], optional): Mapping node
|
|
93
|
+
attribute name and list of their values in order of unique node
|
|
94
|
+
ids. Defaults to None.
|
|
95
|
+
edge_attr (Optional[Dict[str, List[Any]]], optional): Mapping edge
|
|
96
|
+
attribute name and list of their values in order of unique edge
|
|
97
|
+
ids. Defaults to None.
|
|
98
|
+
"""
|
|
99
|
+
self._nodes: Dict[str, int] = dict()
|
|
100
|
+
self._edges: Dict[TripletLike, int] = dict()
|
|
101
|
+
|
|
102
|
+
self._mapped_node_features: Set[str] = set()
|
|
103
|
+
self._mapped_edge_features: Set[str] = set()
|
|
104
|
+
|
|
105
|
+
if len(nodes) != len(set(nodes)):
|
|
106
|
+
raise AttributeError("Nodes need to be unique")
|
|
107
|
+
if len(edges) != len(set(edges)):
|
|
108
|
+
raise AttributeError("Edges need to be unique")
|
|
109
|
+
|
|
110
|
+
if node_attr is not None:
|
|
111
|
+
# TODO: Validity checks btw nodes and node_attr
|
|
112
|
+
self.node_attr = node_attr
|
|
113
|
+
if NODE_KEYS & set(self.node_attr.keys()) != NODE_KEYS:
|
|
114
|
+
raise AttributeError(
|
|
115
|
+
"Invalid node_attr object. Missing " +
|
|
116
|
+
f"{NODE_KEYS - set(self.node_attr.keys())}")
|
|
117
|
+
elif self.node_attr[NODE_PID] != nodes:
|
|
118
|
+
raise AttributeError(
|
|
119
|
+
"Nodes provided do not match those in node_attr")
|
|
120
|
+
else:
|
|
121
|
+
self.node_attr = dict()
|
|
122
|
+
self.node_attr[NODE_PID] = nodes
|
|
123
|
+
|
|
124
|
+
for i, node in enumerate(self.node_attr[NODE_PID]):
|
|
125
|
+
self._nodes[node] = i
|
|
126
|
+
|
|
127
|
+
if edge_attr is not None:
|
|
128
|
+
# TODO: Validity checks btw edges and edge_attr
|
|
129
|
+
self.edge_attr = edge_attr
|
|
130
|
+
|
|
131
|
+
if EDGE_KEYS & set(self.edge_attr.keys()) != EDGE_KEYS:
|
|
132
|
+
raise AttributeError(
|
|
133
|
+
"Invalid edge_attr object. Missing " +
|
|
134
|
+
f"{EDGE_KEYS - set(self.edge_attr.keys())}")
|
|
135
|
+
elif self.node_attr[EDGE_PID] != edges:
|
|
136
|
+
raise AttributeError(
|
|
137
|
+
"Edges provided do not match those in edge_attr")
|
|
138
|
+
|
|
139
|
+
else:
|
|
140
|
+
self.edge_attr = dict()
|
|
141
|
+
for default_key in EDGE_KEYS:
|
|
142
|
+
self.edge_attr[default_key] = list()
|
|
143
|
+
self.edge_attr[EDGE_PID] = edges
|
|
144
|
+
|
|
145
|
+
for tup in edges:
|
|
146
|
+
h, r, t = tup
|
|
147
|
+
self.edge_attr[EDGE_HEAD].append(h)
|
|
148
|
+
self.edge_attr[EDGE_RELATION].append(r)
|
|
149
|
+
self.edge_attr[EDGE_TAIL].append(t)
|
|
150
|
+
self.edge_attr[EDGE_INDEX].append(
|
|
151
|
+
(self._nodes[h], self._nodes[t]))
|
|
152
|
+
for i, tup in enumerate(edges):
|
|
153
|
+
self._edges[tup] = i
|
|
154
|
+
|
|
155
|
+
@classmethod
|
|
156
|
+
def from_triplets(
|
|
157
|
+
cls,
|
|
158
|
+
triplets: KnowledgeGraphLike,
|
|
159
|
+
pre_transform: Optional[Callable[[TripletLike], TripletLike]] = None,
|
|
160
|
+
) -> "LargeGraphIndexer":
|
|
161
|
+
r"""Generate a new index from a series of triplets that represent edge
|
|
162
|
+
relations between nodes.
|
|
163
|
+
Formatted like (source_node, edge, dest_node).
|
|
164
|
+
|
|
165
|
+
Args:
|
|
166
|
+
triplets (KnowledgeGraphLike): Series of triplets representing
|
|
167
|
+
knowledge graph relations. Example: [("cats", "eat", dogs")].
|
|
168
|
+
Note: Please ensure triplets are unique.
|
|
169
|
+
pre_transform (Optional[Callable[[TripletLike], TripletLike]]):
|
|
170
|
+
Optional preprocessing function to apply to triplets.
|
|
171
|
+
Defaults to None.
|
|
172
|
+
|
|
173
|
+
Returns:
|
|
174
|
+
LargeGraphIndexer: Index of unique nodes and edges.
|
|
175
|
+
"""
|
|
176
|
+
# NOTE: Right now assumes that all trips can be loaded into memory
|
|
177
|
+
nodes = []
|
|
178
|
+
edges = []
|
|
179
|
+
|
|
180
|
+
if pre_transform is not None:
|
|
181
|
+
|
|
182
|
+
def apply_transform(
|
|
183
|
+
trips: KnowledgeGraphLike) -> Iterator[TripletLike]:
|
|
184
|
+
for trip in trips:
|
|
185
|
+
yield pre_transform(trip)
|
|
186
|
+
|
|
187
|
+
triplets = list(apply_transform(triplets))
|
|
188
|
+
|
|
189
|
+
for h, r, t in triplets:
|
|
190
|
+
|
|
191
|
+
for node in (h, t):
|
|
192
|
+
nodes.append(node)
|
|
193
|
+
|
|
194
|
+
edge_idx = (h, r, t)
|
|
195
|
+
edges.append(edge_idx)
|
|
196
|
+
nodes = ordered_set(nodes)
|
|
197
|
+
edges = ordered_set(edges)
|
|
198
|
+
return cls(list(nodes), list(edges))
|
|
199
|
+
|
|
200
|
+
@classmethod
|
|
201
|
+
def collate(cls,
|
|
202
|
+
graphs: Iterable["LargeGraphIndexer"]) -> "LargeGraphIndexer":
|
|
203
|
+
r"""Combines a series of large graph indexes into a single large graph
|
|
204
|
+
index.
|
|
205
|
+
|
|
206
|
+
Args:
|
|
207
|
+
graphs (Iterable[LargeGraphIndexer]): Indices to be
|
|
208
|
+
combined.
|
|
209
|
+
|
|
210
|
+
Returns:
|
|
211
|
+
LargeGraphIndexer: Singular unique index for all nodes and edges
|
|
212
|
+
in input indices.
|
|
213
|
+
"""
|
|
214
|
+
# FIXME Needs to merge node attrs and edge attrs?
|
|
215
|
+
trips = chain.from_iterable([graph.to_triplets() for graph in graphs])
|
|
216
|
+
return cls.from_triplets(trips)
|
|
217
|
+
|
|
218
|
+
def get_unique_node_features(self,
|
|
219
|
+
feature_name: str = NODE_PID) -> List[str]:
|
|
220
|
+
r"""Get all the unique values for a specific node attribute.
|
|
221
|
+
|
|
222
|
+
Args:
|
|
223
|
+
feature_name (str, optional): Name of feature to get.
|
|
224
|
+
Defaults to NODE_PID.
|
|
225
|
+
|
|
226
|
+
Returns:
|
|
227
|
+
List[str]: List of unique values for the specified feature.
|
|
228
|
+
"""
|
|
229
|
+
try:
|
|
230
|
+
if feature_name in self._mapped_node_features:
|
|
231
|
+
raise IndexError(
|
|
232
|
+
"Only non-mapped features can be retrieved uniquely.")
|
|
233
|
+
return ordered_set(self.get_node_features(feature_name))
|
|
234
|
+
|
|
235
|
+
except KeyError as e:
|
|
236
|
+
raise AttributeError(
|
|
237
|
+
f"Nodes do not have a feature called {feature_name}") from e
|
|
238
|
+
|
|
239
|
+
def add_node_feature(
|
|
240
|
+
self,
|
|
241
|
+
new_feature_name: str,
|
|
242
|
+
new_feature_vals: FeatureValueType,
|
|
243
|
+
map_from_feature: str = NODE_PID,
|
|
244
|
+
) -> None:
|
|
245
|
+
r"""Adds a new feature that corresponds to each unique node in
|
|
246
|
+
the graph.
|
|
247
|
+
|
|
248
|
+
Args:
|
|
249
|
+
new_feature_name (str): Name to call the new feature.
|
|
250
|
+
new_feature_vals (FeatureValueType): Values to map for that
|
|
251
|
+
new feature.
|
|
252
|
+
map_from_feature (str, optional): Key of feature to map from.
|
|
253
|
+
Size must match the number of feature values.
|
|
254
|
+
Defaults to NODE_PID.
|
|
255
|
+
"""
|
|
256
|
+
if new_feature_name in self.node_attr:
|
|
257
|
+
raise AttributeError("Features cannot be overridden once created")
|
|
258
|
+
if map_from_feature in self._mapped_node_features:
|
|
259
|
+
raise AttributeError(
|
|
260
|
+
f"{map_from_feature} is already a feature mapping.")
|
|
261
|
+
|
|
262
|
+
feature_keys = self.get_unique_node_features(map_from_feature)
|
|
263
|
+
if len(feature_keys) != len(new_feature_vals):
|
|
264
|
+
raise AttributeError(
|
|
265
|
+
"Expected encodings for {len(feature_keys)} unique features," +
|
|
266
|
+
f" but got {len(new_feature_vals)} encodings.")
|
|
267
|
+
|
|
268
|
+
if map_from_feature == NODE_PID:
|
|
269
|
+
self.node_attr[new_feature_name] = new_feature_vals
|
|
270
|
+
else:
|
|
271
|
+
self.node_attr[new_feature_name] = MappedFeature(
|
|
272
|
+
name=map_from_feature, values=new_feature_vals)
|
|
273
|
+
self._mapped_node_features.add(new_feature_name)
|
|
274
|
+
|
|
275
|
+
def get_node_features(
|
|
276
|
+
self,
|
|
277
|
+
feature_name: str = NODE_PID,
|
|
278
|
+
pids: Optional[Iterable[str]] = None,
|
|
279
|
+
) -> List[Any]:
|
|
280
|
+
r"""Get node feature values for a given set of unique node ids.
|
|
281
|
+
Returned values are not necessarily unique.
|
|
282
|
+
|
|
283
|
+
Args:
|
|
284
|
+
feature_name (str, optional): Name of feature to fetch. Defaults
|
|
285
|
+
to NODE_PID.
|
|
286
|
+
pids (Optional[Iterable[str]], optional): Node ids to fetch
|
|
287
|
+
for. Defaults to None, which fetches all nodes.
|
|
288
|
+
|
|
289
|
+
Returns:
|
|
290
|
+
List[Any]: Node features corresponding to the specified ids.
|
|
291
|
+
"""
|
|
292
|
+
if feature_name in self._mapped_node_features:
|
|
293
|
+
values = self.node_attr[feature_name].values
|
|
294
|
+
else:
|
|
295
|
+
values = self.node_attr[feature_name]
|
|
296
|
+
# TODO: torch_geometric.utils.select
|
|
297
|
+
if isinstance(values, torch.Tensor):
|
|
298
|
+
idxs = list(
|
|
299
|
+
self.get_node_features_iter(feature_name, pids,
|
|
300
|
+
index_only=True))
|
|
301
|
+
return values[torch.tensor(idxs).long()]
|
|
302
|
+
return list(self.get_node_features_iter(feature_name, pids))
|
|
303
|
+
|
|
304
|
+
def get_node_features_iter(
|
|
305
|
+
self,
|
|
306
|
+
feature_name: str = NODE_PID,
|
|
307
|
+
pids: Optional[Iterable[str]] = None,
|
|
308
|
+
index_only: bool = False,
|
|
309
|
+
) -> Iterator[Any]:
|
|
310
|
+
"""Iterator version of get_node_features. If index_only is True,
|
|
311
|
+
yields indices instead of values.
|
|
312
|
+
"""
|
|
313
|
+
if pids is None:
|
|
314
|
+
pids = self.node_attr[NODE_PID]
|
|
315
|
+
|
|
316
|
+
if feature_name in self._mapped_node_features:
|
|
317
|
+
feature_map_info = self.node_attr[feature_name]
|
|
318
|
+
from_feature_name, to_feature_vals = (
|
|
319
|
+
feature_map_info.name,
|
|
320
|
+
feature_map_info.values,
|
|
321
|
+
)
|
|
322
|
+
from_feature_vals = self.get_unique_node_features(
|
|
323
|
+
from_feature_name)
|
|
324
|
+
feature_mapping = {k: i for i, k in enumerate(from_feature_vals)}
|
|
325
|
+
|
|
326
|
+
for pid in pids:
|
|
327
|
+
idx = self._nodes[pid]
|
|
328
|
+
from_feature_val = self.node_attr[from_feature_name][idx]
|
|
329
|
+
to_feature_idx = feature_mapping[from_feature_val]
|
|
330
|
+
if index_only:
|
|
331
|
+
yield to_feature_idx
|
|
332
|
+
else:
|
|
333
|
+
yield to_feature_vals[to_feature_idx]
|
|
334
|
+
else:
|
|
335
|
+
for pid in pids:
|
|
336
|
+
idx = self._nodes[pid]
|
|
337
|
+
if index_only:
|
|
338
|
+
yield idx
|
|
339
|
+
else:
|
|
340
|
+
yield self.node_attr[feature_name][idx]
|
|
341
|
+
|
|
342
|
+
def get_unique_edge_features(self,
|
|
343
|
+
feature_name: str = EDGE_PID) -> List[str]:
|
|
344
|
+
r"""Get all the unique values for a specific edge attribute.
|
|
345
|
+
|
|
346
|
+
Args:
|
|
347
|
+
feature_name (str, optional): Name of feature to get.
|
|
348
|
+
Defaults to EDGE_PID.
|
|
349
|
+
|
|
350
|
+
Returns:
|
|
351
|
+
List[str]: List of unique values for the specified feature.
|
|
352
|
+
"""
|
|
353
|
+
try:
|
|
354
|
+
if feature_name in self._mapped_edge_features:
|
|
355
|
+
raise IndexError(
|
|
356
|
+
"Only non-mapped features can be retrieved uniquely.")
|
|
357
|
+
return ordered_set(self.get_edge_features(feature_name))
|
|
358
|
+
except KeyError as e:
|
|
359
|
+
raise AttributeError(
|
|
360
|
+
f"Edges do not have a feature called {feature_name}") from e
|
|
361
|
+
|
|
362
|
+
def add_edge_feature(
|
|
363
|
+
self,
|
|
364
|
+
new_feature_name: str,
|
|
365
|
+
new_feature_vals: FeatureValueType,
|
|
366
|
+
map_from_feature: str = EDGE_PID,
|
|
367
|
+
) -> None:
|
|
368
|
+
r"""Adds a new feature that corresponds to each unique edge in
|
|
369
|
+
the graph.
|
|
370
|
+
|
|
371
|
+
Args:
|
|
372
|
+
new_feature_name (str): Name to call the new feature.
|
|
373
|
+
new_feature_vals (FeatureValueType): Values to map for that new
|
|
374
|
+
feature.
|
|
375
|
+
map_from_feature (str, optional): Key of feature to map from.
|
|
376
|
+
Size must match the number of feature values.
|
|
377
|
+
Defaults to EDGE_PID.
|
|
378
|
+
"""
|
|
379
|
+
if new_feature_name in self.edge_attr:
|
|
380
|
+
raise AttributeError("Features cannot be overridden once created")
|
|
381
|
+
if map_from_feature in self._mapped_edge_features:
|
|
382
|
+
raise AttributeError(
|
|
383
|
+
f"{map_from_feature} is already a feature mapping.")
|
|
384
|
+
|
|
385
|
+
feature_keys = self.get_unique_edge_features(map_from_feature)
|
|
386
|
+
if len(feature_keys) != len(new_feature_vals):
|
|
387
|
+
raise AttributeError(
|
|
388
|
+
f"Expected encodings for {len(feature_keys)} unique features, "
|
|
389
|
+
+ f"but got {len(new_feature_vals)} encodings.")
|
|
390
|
+
|
|
391
|
+
if map_from_feature == EDGE_PID:
|
|
392
|
+
self.edge_attr[new_feature_name] = new_feature_vals
|
|
393
|
+
else:
|
|
394
|
+
self.edge_attr[new_feature_name] = MappedFeature(
|
|
395
|
+
name=map_from_feature, values=new_feature_vals)
|
|
396
|
+
self._mapped_edge_features.add(new_feature_name)
|
|
397
|
+
|
|
398
|
+
def get_edge_features(
|
|
399
|
+
self,
|
|
400
|
+
feature_name: str = EDGE_PID,
|
|
401
|
+
pids: Optional[Iterable[str]] = None,
|
|
402
|
+
) -> List[Any]:
|
|
403
|
+
r"""Get edge feature values for a given set of unique edge ids.
|
|
404
|
+
Returned values are not necessarily unique.
|
|
405
|
+
|
|
406
|
+
Args:
|
|
407
|
+
feature_name (str, optional): Name of feature to fetch.
|
|
408
|
+
Defaults to EDGE_PID.
|
|
409
|
+
pids (Optional[Iterable[str]], optional): Edge ids to fetch
|
|
410
|
+
for. Defaults to None, which fetches all edges.
|
|
411
|
+
|
|
412
|
+
Returns:
|
|
413
|
+
List[Any]: Node features corresponding to the specified ids.
|
|
414
|
+
"""
|
|
415
|
+
if feature_name in self._mapped_edge_features:
|
|
416
|
+
values = self.edge_attr[feature_name].values
|
|
417
|
+
else:
|
|
418
|
+
values = self.edge_attr[feature_name]
|
|
419
|
+
|
|
420
|
+
# TODO: torch_geometric.utils.select
|
|
421
|
+
if isinstance(values, torch.Tensor):
|
|
422
|
+
idxs = list(
|
|
423
|
+
self.get_edge_features_iter(feature_name, pids,
|
|
424
|
+
index_only=True))
|
|
425
|
+
return values[torch.tensor(idxs).long()]
|
|
426
|
+
return list(self.get_edge_features_iter(feature_name, pids))
|
|
427
|
+
|
|
428
|
+
def get_edge_features_iter(
|
|
429
|
+
self,
|
|
430
|
+
feature_name: str = EDGE_PID,
|
|
431
|
+
pids: Optional[KnowledgeGraphLike] = None,
|
|
432
|
+
index_only: bool = False,
|
|
433
|
+
) -> Iterator[Any]:
|
|
434
|
+
"""Iterator version of get_edge_features. If index_only is True,
|
|
435
|
+
yields indices instead of values.
|
|
436
|
+
"""
|
|
437
|
+
if pids is None:
|
|
438
|
+
pids = self.edge_attr[EDGE_PID]
|
|
439
|
+
|
|
440
|
+
if feature_name in self._mapped_edge_features:
|
|
441
|
+
feature_map_info = self.edge_attr[feature_name]
|
|
442
|
+
from_feature_name, to_feature_vals = (
|
|
443
|
+
feature_map_info.name,
|
|
444
|
+
feature_map_info.values,
|
|
445
|
+
)
|
|
446
|
+
from_feature_vals = self.get_unique_edge_features(
|
|
447
|
+
from_feature_name)
|
|
448
|
+
feature_mapping = {k: i for i, k in enumerate(from_feature_vals)}
|
|
449
|
+
|
|
450
|
+
for pid in pids:
|
|
451
|
+
idx = self._edges[pid]
|
|
452
|
+
from_feature_val = self.edge_attr[from_feature_name][idx]
|
|
453
|
+
to_feature_idx = feature_mapping[from_feature_val]
|
|
454
|
+
if index_only:
|
|
455
|
+
yield to_feature_idx
|
|
456
|
+
else:
|
|
457
|
+
yield to_feature_vals[to_feature_idx]
|
|
458
|
+
else:
|
|
459
|
+
for pid in pids:
|
|
460
|
+
idx = self._edges[pid]
|
|
461
|
+
if index_only:
|
|
462
|
+
yield idx
|
|
463
|
+
else:
|
|
464
|
+
yield self.edge_attr[feature_name][idx]
|
|
465
|
+
|
|
466
|
+
def to_triplets(self) -> Iterator[TripletLike]:
|
|
467
|
+
return iter(self.edge_attr[EDGE_PID])
|
|
468
|
+
|
|
469
|
+
def save(self, path: str) -> None:
|
|
470
|
+
if os.path.exists(path):
|
|
471
|
+
shutil.rmtree(path)
|
|
472
|
+
os.makedirs(path, exist_ok=True)
|
|
473
|
+
with open(path + "/edges", "wb") as f:
|
|
474
|
+
pkl.dump(self._edges, f)
|
|
475
|
+
with open(path + "/nodes", "wb") as f:
|
|
476
|
+
pkl.dump(self._nodes, f)
|
|
477
|
+
|
|
478
|
+
with open(path + "/mapped_edges", "wb") as f:
|
|
479
|
+
pkl.dump(self._mapped_edge_features, f)
|
|
480
|
+
with open(path + "/mapped_nodes", "wb") as f:
|
|
481
|
+
pkl.dump(self._mapped_node_features, f)
|
|
482
|
+
|
|
483
|
+
node_attr_path = path + "/node_attr"
|
|
484
|
+
os.makedirs(node_attr_path, exist_ok=True)
|
|
485
|
+
for attr_name, vals in self.node_attr.items():
|
|
486
|
+
torch.save(vals, node_attr_path + f"/{attr_name}.pt")
|
|
487
|
+
|
|
488
|
+
edge_attr_path = path + "/edge_attr"
|
|
489
|
+
os.makedirs(edge_attr_path, exist_ok=True)
|
|
490
|
+
for attr_name, vals in self.edge_attr.items():
|
|
491
|
+
torch.save(vals, edge_attr_path + f"/{attr_name}.pt")
|
|
492
|
+
|
|
493
|
+
@classmethod
|
|
494
|
+
def from_disk(cls, path: str) -> "LargeGraphIndexer":
|
|
495
|
+
indexer = cls(list(), list())
|
|
496
|
+
with open(path + "/edges", "rb") as f:
|
|
497
|
+
indexer._edges = pkl.load(f)
|
|
498
|
+
with open(path + "/nodes", "rb") as f:
|
|
499
|
+
indexer._nodes = pkl.load(f)
|
|
500
|
+
|
|
501
|
+
with open(path + "/mapped_edges", "rb") as f:
|
|
502
|
+
indexer._mapped_edge_features = pkl.load(f)
|
|
503
|
+
with open(path + "/mapped_nodes", "rb") as f:
|
|
504
|
+
indexer._mapped_node_features = pkl.load(f)
|
|
505
|
+
|
|
506
|
+
node_attr_path = path + "/node_attr"
|
|
507
|
+
for fname in os.listdir(node_attr_path):
|
|
508
|
+
full_fname = f"{node_attr_path}/{fname}"
|
|
509
|
+
key = fname.split(".")[0]
|
|
510
|
+
indexer.node_attr[key] = fs.torch_load(full_fname)
|
|
511
|
+
|
|
512
|
+
edge_attr_path = path + "/edge_attr"
|
|
513
|
+
for fname in os.listdir(edge_attr_path):
|
|
514
|
+
full_fname = f"{edge_attr_path}/{fname}"
|
|
515
|
+
key = fname.split(".")[0]
|
|
516
|
+
indexer.edge_attr[key] = fs.torch_load(full_fname)
|
|
517
|
+
|
|
518
|
+
return indexer
|
|
519
|
+
|
|
520
|
+
def to_data(self, node_feature_name: str,
|
|
521
|
+
edge_feature_name: Optional[str] = None) -> Data:
|
|
522
|
+
"""Return a Data object containing all the specified node and
|
|
523
|
+
edge features and the graph.
|
|
524
|
+
|
|
525
|
+
Args:
|
|
526
|
+
node_feature_name (str): Feature to use for nodes
|
|
527
|
+
edge_feature_name (Optional[str], optional): Feature to use for
|
|
528
|
+
edges. Defaults to None.
|
|
529
|
+
|
|
530
|
+
Returns:
|
|
531
|
+
Data: Data object containing the specified node and
|
|
532
|
+
edge features and the graph.
|
|
533
|
+
"""
|
|
534
|
+
x = torch.Tensor(self.get_node_features(node_feature_name))
|
|
535
|
+
node_id = torch.LongTensor(range(len(x)))
|
|
536
|
+
edge_index = torch.t(
|
|
537
|
+
torch.LongTensor(self.get_edge_features(EDGE_INDEX)))
|
|
538
|
+
|
|
539
|
+
edge_attr = (self.get_edge_features(edge_feature_name)
|
|
540
|
+
if edge_feature_name is not None else None)
|
|
541
|
+
edge_id = torch.LongTensor(range(len(edge_attr)))
|
|
542
|
+
|
|
543
|
+
return Data(x=x, edge_index=edge_index, edge_attr=edge_attr,
|
|
544
|
+
edge_id=edge_id, node_id=node_id)
|
|
545
|
+
|
|
546
|
+
def __eq__(self, value: "LargeGraphIndexer") -> bool:
|
|
547
|
+
eq = True
|
|
548
|
+
eq &= self._nodes == value._nodes
|
|
549
|
+
eq &= self._edges == value._edges
|
|
550
|
+
eq &= self.node_attr.keys() == value.node_attr.keys()
|
|
551
|
+
eq &= self.edge_attr.keys() == value.edge_attr.keys()
|
|
552
|
+
eq &= self._mapped_node_features == value._mapped_node_features
|
|
553
|
+
eq &= self._mapped_edge_features == value._mapped_edge_features
|
|
554
|
+
|
|
555
|
+
for k in self.node_attr:
|
|
556
|
+
eq &= isinstance(self.node_attr[k], type(value.node_attr[k]))
|
|
557
|
+
if isinstance(self.node_attr[k], torch.Tensor):
|
|
558
|
+
eq &= torch.equal(self.node_attr[k], value.node_attr[k])
|
|
559
|
+
else:
|
|
560
|
+
eq &= self.node_attr[k] == value.node_attr[k]
|
|
561
|
+
for k in self.edge_attr:
|
|
562
|
+
eq &= isinstance(self.edge_attr[k], type(value.edge_attr[k]))
|
|
563
|
+
if isinstance(self.edge_attr[k], torch.Tensor):
|
|
564
|
+
eq &= torch.equal(self.edge_attr[k], value.edge_attr[k])
|
|
565
|
+
else:
|
|
566
|
+
eq &= self.edge_attr[k] == value.edge_attr[k]
|
|
567
|
+
return eq
|
|
568
|
+
|
|
569
|
+
|
|
570
|
+
def get_features_for_triplets_groups(
|
|
571
|
+
indexer: LargeGraphIndexer,
|
|
572
|
+
triplet_groups: Iterable[KnowledgeGraphLike],
|
|
573
|
+
node_feature_name: str = "x",
|
|
574
|
+
edge_feature_name: str = "edge_attr",
|
|
575
|
+
pre_transform: Callable[[TripletLike], TripletLike] = lambda trip: trip,
|
|
576
|
+
verbose: bool = False,
|
|
577
|
+
max_batch_size: int = 250,
|
|
578
|
+
num_workers: Optional[int] = None,
|
|
579
|
+
) -> Iterator[Data]:
|
|
580
|
+
"""Given an indexer and a series of triplet groups (like a dataset),
|
|
581
|
+
retrieve the specified node and edge features for each triplet from the
|
|
582
|
+
index.
|
|
583
|
+
|
|
584
|
+
Args:
|
|
585
|
+
indexer (LargeGraphIndexer): Indexer containing desired features
|
|
586
|
+
triplet_groups (Iterable[KnowledgeGraphLike]): List of lists of
|
|
587
|
+
triplets to fetch features for
|
|
588
|
+
node_feature_name (str, optional): Node feature to fetch.
|
|
589
|
+
Defaults to "x".
|
|
590
|
+
edge_feature_name (str, optional): edge feature to fetch.
|
|
591
|
+
Defaults to "edge_attr".
|
|
592
|
+
pre_transform (Callable[[TripletLike], TripletLike]):
|
|
593
|
+
Optional preprocessing to perform on triplets.
|
|
594
|
+
Defaults to None.
|
|
595
|
+
verbose (bool, optional): Whether to print progress.
|
|
596
|
+
Defaults to False.
|
|
597
|
+
max_batch_size (int, optional):
|
|
598
|
+
Maximum batch size for fetching features.
|
|
599
|
+
Defaults to 250.
|
|
600
|
+
num_workers (int, optional):
|
|
601
|
+
Number of workers to use for fetching features.
|
|
602
|
+
Defaults to None (all available).
|
|
603
|
+
|
|
604
|
+
Yields:
|
|
605
|
+
Iterator[Data]: For each triplet group, yield a data object containing
|
|
606
|
+
the unique graph and features from the index.
|
|
607
|
+
"""
|
|
608
|
+
def apply_transform(trips: Iterable[TripletLike]) -> Iterator[TripletLike]:
|
|
609
|
+
for trip in trips:
|
|
610
|
+
yield pre_transform(tuple(trip))
|
|
611
|
+
|
|
612
|
+
# Carefully trying to avoid loading all triplets into memory at once
|
|
613
|
+
# While also still tracking the number of elements for tqdm
|
|
614
|
+
triplet_groups: List[Iterator[TripletLike]] = [
|
|
615
|
+
apply_transform(triplets) for triplets in triplet_groups
|
|
616
|
+
]
|
|
617
|
+
|
|
618
|
+
node_keys = []
|
|
619
|
+
edge_keys = []
|
|
620
|
+
edge_index = []
|
|
621
|
+
"""
|
|
622
|
+
For each KG, we gather the node_indices, edge_keys,
|
|
623
|
+
and edge_indices needed to construct each Data object
|
|
624
|
+
"""
|
|
625
|
+
|
|
626
|
+
for kg_triplets in tqdm(triplet_groups, disable=not verbose):
|
|
627
|
+
kg_triplets_nodes, kg_triplets_edge_keys, kg_triplets_edge_index = tee(
|
|
628
|
+
kg_triplets, 3)
|
|
629
|
+
"""
|
|
630
|
+
Don't apply pre_transform here,
|
|
631
|
+
because it has already been applied on the triplet groups/
|
|
632
|
+
"""
|
|
633
|
+
small_graph_indexer = LargeGraphIndexer.from_triplets(
|
|
634
|
+
kg_triplets_nodes)
|
|
635
|
+
|
|
636
|
+
node_keys.append(small_graph_indexer.get_node_features())
|
|
637
|
+
edge_keys.append(
|
|
638
|
+
small_graph_indexer.get_edge_features(pids=kg_triplets_edge_keys))
|
|
639
|
+
edge_index.append(
|
|
640
|
+
small_graph_indexer.get_edge_features(
|
|
641
|
+
EDGE_INDEX,
|
|
642
|
+
kg_triplets_edge_index,
|
|
643
|
+
))
|
|
644
|
+
"""
|
|
645
|
+
We get the embeddings for each node and edge key in the KG,
|
|
646
|
+
but we need to do so in batches.
|
|
647
|
+
Batches that are too small waste compute time,
|
|
648
|
+
as each call to get features has an upfront cost.
|
|
649
|
+
Batches that are too large waste memory,
|
|
650
|
+
as we need to store all the result embeddings in memory.
|
|
651
|
+
"""
|
|
652
|
+
|
|
653
|
+
def _fetch_feature_batch(batches):
|
|
654
|
+
node_key_batch, edge_key_batch, edge_index_batch = batches
|
|
655
|
+
node_feats = indexer.get_node_features(
|
|
656
|
+
feature_name=node_feature_name,
|
|
657
|
+
pids=chain.from_iterable(node_key_batch))
|
|
658
|
+
edge_feats = indexer.get_edge_features(
|
|
659
|
+
feature_name=edge_feature_name,
|
|
660
|
+
pids=chain.from_iterable(edge_key_batch))
|
|
661
|
+
|
|
662
|
+
last_node_idx, last_edge_idx = 0, 0
|
|
663
|
+
for (nkeys, ekeys, eidx) in zip(node_key_batch, edge_key_batch,
|
|
664
|
+
edge_index_batch):
|
|
665
|
+
nlen, elen = len(nkeys), len(ekeys)
|
|
666
|
+
x = torch.Tensor(node_feats[last_node_idx:last_node_idx + nlen])
|
|
667
|
+
last_node_idx += len(nkeys)
|
|
668
|
+
|
|
669
|
+
edge_attr = torch.Tensor(edge_feats[last_edge_idx:last_edge_idx +
|
|
670
|
+
elen])
|
|
671
|
+
last_edge_idx += len(ekeys)
|
|
672
|
+
|
|
673
|
+
edge_idx = torch.LongTensor(eidx).T
|
|
674
|
+
|
|
675
|
+
data_obj = Data(x=x, edge_attr=edge_attr, edge_index=edge_idx)
|
|
676
|
+
data_obj[NODE_PID] = node_keys
|
|
677
|
+
data_obj[EDGE_PID] = edge_keys
|
|
678
|
+
data_obj["node_idx"] = [indexer._nodes[k] for k in nkeys]
|
|
679
|
+
data_obj["edge_idx"] = [indexer._edges[e] for e in ekeys]
|
|
680
|
+
|
|
681
|
+
yield data_obj
|
|
682
|
+
|
|
683
|
+
# NOTE: Backport of itertools.batched from Python 3.12
|
|
684
|
+
def batched(iterable, n, *, strict=False):
|
|
685
|
+
# batched('ABCDEFG', 3) → ABC DEF G
|
|
686
|
+
if n < 1:
|
|
687
|
+
raise ValueError('n must be at least one')
|
|
688
|
+
iterator = iter(iterable)
|
|
689
|
+
while batch := tuple(islice(iterator, n)):
|
|
690
|
+
if strict and len(batch) != n:
|
|
691
|
+
raise ValueError('batched(): incomplete batch')
|
|
692
|
+
yield batch
|
|
693
|
+
|
|
694
|
+
import multiprocessing as mp
|
|
695
|
+
import multiprocessing.pool as mpp
|
|
696
|
+
num_workers = num_workers if num_workers is not None else mp.cpu_count()
|
|
697
|
+
ideal_batch_size = min(max_batch_size,
|
|
698
|
+
max(1,
|
|
699
|
+
len(triplet_groups) // num_workers))
|
|
700
|
+
|
|
701
|
+
node_key_batches = batched(node_keys, ideal_batch_size)
|
|
702
|
+
edge_key_batches = batched(edge_keys, ideal_batch_size)
|
|
703
|
+
edge_index_batches = batched(edge_index, ideal_batch_size)
|
|
704
|
+
batches = zip(node_key_batches, edge_key_batches, edge_index_batches)
|
|
705
|
+
|
|
706
|
+
with mpp.ThreadPool() as pool:
|
|
707
|
+
result = pool.map(_fetch_feature_batch, batches)
|
|
708
|
+
yield from chain.from_iterable(result)
|
|
709
|
+
|
|
710
|
+
|
|
711
|
+
def get_features_for_triplets(
|
|
712
|
+
indexer: LargeGraphIndexer,
|
|
713
|
+
triplets: KnowledgeGraphLike,
|
|
714
|
+
node_feature_name: str = "x",
|
|
715
|
+
edge_feature_name: str = "edge_attr",
|
|
716
|
+
pre_transform: Callable[[TripletLike], TripletLike] = lambda trip: trip,
|
|
717
|
+
verbose: bool = False,
|
|
718
|
+
) -> Data:
|
|
719
|
+
"""For a given set of triplets retrieve a Data object containing the
|
|
720
|
+
unique graph and features from the index.
|
|
721
|
+
|
|
722
|
+
Args:
|
|
723
|
+
indexer (LargeGraphIndexer): Indexer containing desired features
|
|
724
|
+
triplets (KnowledgeGraphLike): Triplets to fetch features for
|
|
725
|
+
node_feature_name (str, optional): Feature to use for node features.
|
|
726
|
+
Defaults to "x".
|
|
727
|
+
edge_feature_name (str, optional): Feature to use for edge features.
|
|
728
|
+
Defaults to "edge_attr".
|
|
729
|
+
pre_transform (Callable[[TripletLike], TripletLike]):
|
|
730
|
+
Optional preprocessing function for triplets. Defaults to None.
|
|
731
|
+
verbose (bool, optional): Whether to print progress. Defaults to False.
|
|
732
|
+
|
|
733
|
+
Returns:
|
|
734
|
+
Data: Data object containing the unique graph and features from the
|
|
735
|
+
index for the given triplets.
|
|
736
|
+
"""
|
|
737
|
+
gen = get_features_for_triplets_groups(indexer, [triplets],
|
|
738
|
+
node_feature_name,
|
|
739
|
+
edge_feature_name, pre_transform,
|
|
740
|
+
verbose, max_batch_size=1)
|
|
741
|
+
return next(gen)
|